TextField 有一个很好的方法来在它的 BoxDecoration 装饰上放置一个文本标签,如下:
通过以下方式:
1 2 3 4 5 6 7 8 9 |
TextField( onTap: onTap, controller: controller, decoration: InputDecoration( labelText: "XP", border: OutlineInputBorder( borderRadius: BorderRadius.circular(50.0), ), )); |
有没有办法在 Container 的其他 BoxDecoration 上实现同样的效果?例如,我想指定标签"XP":
1 2 3 4 5 6 7 8 |
Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(5)), border: Border.all(color: color, width: 2.0), labelText: Text("XP"), // No such attribute ), child: child, ), |
但是 Flutter 没有为 BoxDecoration 提供 labelText (仅存在于 InputDecoration )。
我们可以使用 InputDecorator 作为父对象来完成上述需求,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const Home(), debugShowCheckedModeBanner: false, ); } } class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: 100, width: 400, child: InputDecorator( decoration: InputDecoration( labelText: 'XP', border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), )), child: Text("Container Content"), ), ), ), ); } } |
输出