One month ago, “More than one million StackOverflow Flutter problems — The first issue” was shared by many friends. Thank you for your support.
No connected devices
This problem is estimated that most have encountered, the solution is as follows:
-
Perform flutter doctor
Doctor summary (to see all details, run flutter Doctor -V): [✓] flutter (Channel stable, v1)12.13.+hotfix9..on Mac OS X 10.146. 18G1012, locale zh-Hans-CN) [!] Android toolchain - developfor Android devices (Android SDK version 29.02.)! Some Android licenses not accepted. To resolvethis, run: flutter doctor --android-licenses [✓] Xcode - develop for iOS and macOS (Xcode 11.31.[✓] Android Studio (version)3.5[✓] Connected device ()1 available) ! Doctor found issues in 1 category. Copy the code
Make sure there are no red crosses.
-
Start the mobile phone or emulator (Android > 16) and enable THE USB debugging mode. The enabling method varies with different mobile phones. Take Huawei mobile phones as an example: Enter Settings -> System -> About mobile phone, quickly click the version number for 5 times in succession, prompting to open developer mode, and return to Settings. At this time, developer options menu will appear. Enter, open Developer options and USB debugging, and the authorization menu will pop up.
-
Open Android Studio and view connected phones:
-
If you still can’t connect to your phone, open the Android Studio Settings screen:
Select the most recent API.
-
If you cannot connect to adb, you may have an ADB port that is occupied. There are many ways to cause ADB problems.
Create a Toast prompt
In the Material Design specification, Snackbars are Toast hints, and Snackbars are used as follows:
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Sending Message")));Copy the code
This effect is not well accepted in China, so the third party plugin Fluttertoast is generally used
Fluttertoast.showToast(
msg: "This is Toast messaget",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
Copy the code
Create a Button with rounded corners
There are many ways to create a Button with rounded corners. Here are some simple ones:
-
Use FlatButton and RaisedButton
shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), side: BorderSide(color: Colors.red) ), Copy the code
-
Using ClipRRect
ClipRRect( borderRadius: BorderRadius.circular(40), child: RaisedButton( onPressed: () {}, child: Text("Button"),),)Copy the code
-
Using ButtonTheme
ButtonTheme( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), child: RaisedButton( onPressed: () {}, child: Text("Button"),),)Copy the code
Add a startup page
Flutter application starts when a white during a period of time, because the program to start the engine, so the App the first time you start slowly, on the primary side white start page will display a period of time, we put the white start page as the starting page of the application, replace with your own images, this plan start page is only a picture, not interaction, It is recommended to use Flutter if you want to start the page to have interactive effects.
Android end to replace start page picture, open the Android/app/SRC/main/res/drawable/launch_background. XML file, the results are as follows:
<? xml version="1.0" encoding="utf-8"? > <! -- Modifythis file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white"/ > <! -- You can insert your own image assets here --> <! -- <item> <bitmap android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
Copy the code
Is amended as:
<? xml version="1.0" encoding="utf-8"? > <! -- Modifythis file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<bitmap
android:gravity="center"
android:src="@drawable/splash" />
</item>
</layer-list>
Copy the code
Copy the splash. PNG image to the Drawable folder.
The iOS side, open the iOS/Runner/Assets. Xcassets/LaunchImage imageset. The following three LaunchImage PNG image substitution, the name unchanged.
Modify the package name /BundleIdentifier for the application
Open Android /app/build.gradle:
defaultConfig {
applicationId "com.example.fluttersample"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
Copy the code
Modify the applicationId attribute.
IOS Platform Open iOS /Runner/ info. plist and change the CFBundleIdentifier value:
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
Copy the code
How do I add borders to a control
New Container(margin: const EdgeInsets. All (15.0), padding: const EdgeInsets. All (3.0), decoration: BoxDecoration( border: Border.all(color: Colors.blueAccent) ), child: Text("My Awesome Border"), )Copy the code
Fill the Button with the parent component
SizedBox.expand(
child: RaisedButton(...),
)
Copy the code
or
SizedBox(
width: double.infinity,
// height: double.infinity,
child: RaisedButton(...),
)
Copy the code
or
ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: RaisedButton(...),
)
Copy the code
or
ButtonTheme(
minWidth: double.infinity,
child: MaterialButton(
onPressed: () {},
child: Text('Raised Button'),),),Copy the code
How do I add a ListView to Column
Assign height to ListView:
Column(
children: <Widget>[
Container(
height: 50,
child: ListView(),
)
],
)
Copy the code
Or Column:
Column(
children: <Widget>[
Expanded(
child: horizontalList,
)
],
);
Copy the code
How to add rounded corners to an image
ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(
' ',),)Copy the code
or
CircleAvatar(
radius: 20,
backgroundImage: NetworkImage('https://via.placeholder.com/140x100'))Copy the code
or
ClipOval(
child: Image.network(
"image_url",
height: 100,
width: 100,
fit: BoxFit.cover,
),
),
Copy the code
or
Container(
width: 100.0,
height: 150.0,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage('Path to your image')
),
borderRadius: BorderRadius.all(Radius.circular(8.0)),
color: Colors.redAccent,
),
Copy the code
How to remove the underline from TextField
InputDecoration(
border: InputBorder.none,
hintText: 'Username',
),
),
Copy the code
How to prevent the UI from switching between horizontal and vertical screens as the phone rotates
Set supported directions:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return new MaterialApp(...);
}
}
Copy the code
Open ios/Runner/ info.plist and set supported directions:
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
Copy the code
Show/hide controls
Use the Opacity
Opacity(
opacity: . 0,
child: ,
)
Copy the code
or
Visibility(
visible: false,
child: ,
)
Copy the code
or
Offstage(
offstage: true,
child: ,
)
Copy the code
How to intercept Android’s back button and handle it
Using WillPopScope
@override
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async= >false,
child: new Scaffold(
appBar: new AppBar(
title: new Text("data"),
leading: new IconButton(
icon: new Icon(Icons.ac_unit),
onPressed: () => Navigator.of(context).pop(),
),
),
),
);
}
Copy the code
How to set the Width of the RaisedButton control
ButtonTheme(minWidth: 200.0, height: 100.0, Child: RaisedButton(onPressed: () {}, child: Text("test"),);Copy the code
or
SizedBox(
width: 100, // specific value
child: RaisedButton(...)
)
Copy the code
Set AppBar height
Use the PreferredSize:
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Example', home: Scaffold( appBar: PreferredSize( preferredSize: // The desired height child: AppBar(//... ), body: // ... ) ); }}Copy the code
How to Format time
The Dart API itself does not have an interface for formatting time, using INTL:
import 'package:intl/intl.dart';
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy - MM - dd - kk: MM').format(now);
Copy the code
Draws a set of controls through a List
Widget getTextWidgets(List<String> strings)
{
List<Widget> list = new List<Widget>();
for(var i = 0; i < strings.length; i++){
list.add(new Text(strings[i]));
}
return new Row(children: list);
}
Copy the code
or
Row(children: strings.map((item) => new Text(item)).toList())
Copy the code
or
var list = ["one", "two", "three", "four"];
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for(var item in list ) Text(item)
],
),
Copy the code
How to set the height of a component in the GridView
Use childAspectRatio as follows:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> widgetList = ['A'.'B'.'C'];
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
/*24 is for notification bar on Android*/
final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
final double itemWidth = size.width / 2;
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Container(
child: new GridView.count(
crossAxisCount: 2,
childAspectRatio: (itemWidth / itemHeight),
controller: new ScrollController(keepScrollOffset: false),
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: widgetList.map((String value) {
return new Container(
color: Colors.green,
margin: new EdgeInsets.all(1.0),
child: new Center(
child: new Text(
value,
style: new TextStyle(
fontSize: 50.0, color: Colors.white, ), ), ), ); }).toList(), ), ), ); }}Copy the code
How do I change the color of the status bar
Using flutter_statusbarcolor
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
FlutterStatusbarcolor.setStatusBarColor(Colors.white);
returnMaterialApp( title: app_title, theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(title: home_title), ); }}Copy the code
or
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.white
));
Copy the code
Column’s child controls are centered at the bottom and aligned to the left
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
//your elements here]);Copy the code
communication
Old Meng Flutter blog address (nearly 200 controls usage) : laomengit.com
Over a million StackOverflow Flutter problems – Issue 1