前言
在当今的移动应用开发领域,Flutter 作为一个领先的跨平台开发框架,以其高效和优雅的设计赢得了广泛的关注与应用。在 Flutter 中,开发者可以利用丰富的内置组件迅速构建出引人注目的用户界面。本文档将介绍 Flutter 中的一些基本组件和代码示例,帮助开发者更好地理解如何在应用中实现常见的 UI 元素
代码存储
跳转
import 'dart:js'; import 'package:flutter/material.dart'; class myApp2 extends StatelessWidget{ const myApp2({super.key}); @override Widget build(BuildContext context) { return MaterialApp( routes:{ "/":(BuildContext context) => Example202A(), "/second":(BuildContext context)=>Example202B(), } ); } } class Example202A extends StatefulWidget{ const Example202A({super.key}); @override State<StatefulWidget> createState() { return _ExampleAState(); } } class _ExampleAState extends State<Example202A>{ String result=""; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('A page'), ), body:Column( children: [ ElevatedButton(onPressed: ()=>{openBpage()}, child: Text('open B page')), ElevatedButton(onPressed: ()=>{openBparams()}, child: Text('open B page and get the B params')), Container(child: Text('the B page params is:$result'),) ], ) , ); } } class Example202B extends StatefulWidget { const Example202B({super.key}); @override State<StatefulWidget> createState() { return _ExampleBState(); } } class _ExampleBState extends State<Example202B>{ String _msg=""; @override void initState(){ super.initState(); @override void didChangeDependencies(){ super.didChangeDependencies(); bool isFirst=ModalRoute.of(context as BuildContext)!.isFirst; bool isCurrent=ModalRoute.of(context as BuildContext)!.isCurrent; bool isActive=ModalRoute.of(context as BuildContext)!.isActive; if(isActive){ RouteSettings routeSettings=ModalRoute.of(context as BuildContext)!.settings; Map<String,String>?arguments=routeSettings.arguments as Map<String, String>?; _msg=arguments.toString(); } }; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('B page'),), body: Column( children: [ ElevatedButton(onPressed: ()=>{closeBpage()}, child:Text('close the current page')), SizedBox(height: 20), Text('the msg is :$_msg') ], ), ); } } //open b void openBpage(){ Map<String,String>map=new Map(); map["name"]="youren"; // 跳转第二个页面参数 Navigator.of(context as BuildContext).pushNamed("/second",arguments: map); } //open b and get params void openBparams(){ Map<String,String>map=new Map(); map["name"]="youren"; Navigator.of(context as BuildContext).pushNamed("/second",arguments: map).then((value){ if(value != null){ Map<String,String>?resultMap=value as Map<String, String>?; print("the result is ${resultMap?['result']}"); // setState((){ // result=resultMap.toString(); // }); } }); } void closeBpage(){ Map<String,String>resultMap=new Map(); resultMap["result"]="ABCDE"; Navigator.of(context as BuildContext).pop(resultMap); } void main(){ runApp(const myApp2()); }
基本组件
head
Appbar
简单使用
return Scaffold( //leading 表示左侧 actions 表示右侧 appBar: AppBar( // 左侧按钮 leading: IconButton(icon: const Icon(Icons.close),onPressed: (){},), // 中间显示的内容 title:const Text( "i am the title"), // title 居中 centerTitle: true, actions: [ IconButton(icon: const Icon(Icons.share),onPressed: (){},), IconButton(icon: const Icon(Icons.message),onPressed: (){},), IconButton(icon: const Icon(Icons.more_horiz_outlined),onPressed: (){},), ], ), );
实现可滑动切换的标签栏
import 'package:flutter/material.dart'; class Echo extends StatefulWidget{ @override State<StatefulWidget> createState() { return _Echo(); } } class _Echo extends State <Echo> with SingleTickerProviderStateMixin{ // 控制器 late TabController _tabController; // tab 集合 List<Tab> tabs= <Tab>[]; //主体页面集合 List<Widget> bodyList = []; @override void initState(){ super.initState(); // 初始化 Tab 如新闻咨询类 App 分类 tabs=<Tab>[ Tab(text: "Tab0",), Tab(text: "Tab1",), Tab(text: "Tab3",), Tab(text: "Tab4",), ]; // 创建模拟页面 如 app分类 列表 for(int i= 0;i<tabs.length;i++){ bodyList.add(tabs(i)); } // 参数 1 initialIndex 初始选中几个 // 2 length 标签的个数 // 3 vsync 动画同步依赖 _tabController=TabController(length: tabs.length, vsync: this,initialIndex: 0); } @override Widget build(BuildContext context){ return Scaffold( //leading 表示左侧 actions 表示右侧 appBar: AppBar( // 左侧按钮 leading: IconButton(icon: const Icon(Icons.close),onPressed: (){},), // 中间显示的内容 title:TabBar( controller: _tabController, tabs: tabs,isScrollable: false, ), // title 居中 centerTitle: true, ), body:TabBarView( controller: _tabController, children: bodyList, ) ); } } void main(List<String> args){ runApp(MaterialApp( title: 'hello', home: Echo(), )); }
TextField
简单使用
所有的参数
加边框
属性
Widget buildTextField(){ return TextField( // type keyboardType: TextInputType.text, // when you get in the page ,it will focus this autofocus: true, // secret can't see it // obscureText: true, maxLength: 11, // InputDecoration decoration: InputDecoration( labelText: "input your number", hintStyle: TextStyle( color: Colors.grey,fontSize: 12.0 ), // border border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(40)) ) ), ); }
prefixIcon suffixIcon
登录页面
import 'package:flutter/material.dart'; import './test.dart'; class test extends StatefulWidget{ const test({Key? key}) : super(key: key); @override State<StatefulWidget> createState() =>_test(); } class _test extends State<test> { @override Widget build(BuildContext context) { return Scaffold( appBar:AppBar(title: Text('login'),), body:Container( margin: const EdgeInsets.all(30.0), child: Column( children: [ const TextField( decoration: InputDecoration( labelText: 'username', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)) ) ), ), const SizedBox(height: 20), const TextField( obscureText: true, maxLines: 1, decoration: InputDecoration( labelText: 'password', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)) ) ), ), const SizedBox(height: 20), ElevatedButton(child:const Text('login',),onPressed: (){ // Navigator.of(context).pushNamed( "successful"); Navigator.push(context, MaterialPageRoute(builder: (context){ return Successful(); })); },), ], ), ) ); } } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return MaterialApp( title: "hello", initialRoute: "/", routes: { "/":(context)=>test(), "successful":(context)=>Successful(), }, ); } } void main(){ runApp(const MyApp()); }
文本控制器
监听
在当前的widget下 FocusNode focusNode = new FocusNode(); focusNode: focusNode, @override void initState(){ super.initState(); // addListener(); focusNode.addListener((){ if(focusNode.hasFocus){ print("get focus"); }else{ print("lost focus"); } }); }
//页面销毁 @override void dispose(){ super.dispose(); focusNode.dispose(); }
点击空白隐藏键盘
return GestureDetector( onTap: (){ SystemChannels.textInput.invokeMethod('TextInput.hide'); }, );
TextEditingControll
TextEditingController _usernameController= new TextEditingController(); controller: _usernameController, String res= _usernameController.text
使用
import 'package:flutter/material.dart'; class test01 extends StatefulWidget { const test01({Key? key}) : super(key: key); @override State<test01> createState() => _test01State(); } class _test01State extends State<test01> { FocusNode focusNode = new FocusNode(); // focusNode: focusNode, TextEditingController _usernameController= new TextEditingController(); @override void initState() { super.initState(); // addListener(); focusNode.addListener(() { if (focusNode.hasFocus) { print("get focus"); } else { print("lost focus"); } }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("title"),), body: Center( child: Column( children: [ TextField( focusNode: focusNode, controller: _usernameController, obscureText: true, maxLines: 1, decoration: InputDecoration( labelText: 'password', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)))), ), ElevatedButton(onPressed: (){ String res= _usernameController.text; print(res); }, child: Text("click me")) ], ), ), ); } }
修饰
加边框
borderRadious:BorderRadius.all(Radius.circular(10)
return TextField( decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)) ) ), );
给提示信息 labelText: "input something", hintText: "input something2",
// 密码框显示 obscureText: true,