Introduction to Old Meng Today, I’m going to share 20 of the most popular StackOverflow questions. These questions give me a very familiar feeling. I’m sure you’ve come across some of the most popular questions on StackOverflow. Share it every two weeks.

How to implement wrap_content and match_parent in Android

You can do this as follows:

1, Width =Wrap_content Height=Wrap_content:

Wrap(
  children: <Widget>[your_child])
Copy the code

Width =Match_parent Height=Match_parent:

Container(
        height: double.infinity,
    width: double.infinity,child:your_child)
Copy the code

3, Width = Match_parent,Height = Wrap_conten:

Row(
  mainAxisSize: MainAxisSize.max,
  children: <Widget>[*your_child*],
);
Copy the code

4, Width = Wrap_content,Height = Match_parent:

Column(
  mainAxisSize: MainAxisSize.max,
  children: <Widget>[your_child],
);
Copy the code

How do I avoid FutureBuilder execution too oftenfuturemethods

Incorrect usage:

@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: httpCall(),
    builder: (context, snapshot) {
     
    },
  );
}
Copy the code

Correct usage:

class _ExampleState extends State<Example> {
  Future<int> future;

  @override
  void initState() {
    future = Future.value(42);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    returnFutureBuilder( future: future, builder: (context, snapshot) { }, ); }}Copy the code

Bottom navigation switch causes reconstruction problems

Bottom navigation is often written as follows:

Widget _currentBody;

@override
Widget build(BuildContext context) {
  returnScaffold( body: _currentBody, bottomNavigationBar: BottomNavigationBar( items: <BottomNavigationBarItem>[ ... ] , onTap: (index) { _bottomNavigationChange(index); },),); } _bottomNavigationChange(int index) {
  switch (index) {
    case 0:
      _currentBody = OnePage();
      break;
    case 1:
      _currentBody = TwoPage();
      break;
    case 2:
      _currentBody = ThreePage();
      break;
  }
  setState(() {});
}
Copy the code

This usage causes the page to be rebuilt with each switch.

To resolve this, use IndexedStack:

int _currIndex;

@override
Widget build(BuildContext context) {
  returnScaffold( body: IndexedStack( index: _currIndex, children: <Widget>[OnePage(), TwoPage(), ThreePage()], ), bottomNavigationBar: BottomNavigationBar( items: <BottomNavigationBarItem>[ ... ] , onTap: (index) { _bottomNavigationChange(index); },),); } _bottomNavigationChange(int index) {
  setState(() {
      _currIndex = index;
    });
}
Copy the code

TabBar switching causes build problems

In general, TabBarView is used as follows:

TabBarView(
  controller: this._tabController,
  children: <Widget>[
    _buildTabView1(),
    _buildTabView2(),
  ],
)
Copy the code

When you switch to TAB, the page will be rebuilt.

var _newsKey = PageStorageKey('news');
var _technologyKey = PageStorageKey('technology');

TabBarView(
  controller: this._tabController,
  children: <Widget>[
    _buildTabView1(_newsKey),
    _buildTabView2(_technologyKey),
  ],
)
Copy the code

The width and height of the Stack child does not work

Set the 100×100 red box in the Stack as follows:

Center(
  child: Container(
    height: 300,
    width: 300,
    color: Colors.blue,
    child: Stack(
      children: <Widget>[
        Positioned.fill(
          child: Container(
            height: 100,
            width: 100,
            color: Colors.red,
          ),
        )
      ],
    ),
  ),
)
Copy the code

The red box is filled with the parent component. The solution is to wrap the red box with Center, Align, or UnconstrainedBox as follows:

Positioned.fill(
  child: Align(
    child: Container(
      height: 100,
      width: 100,
      color: Colors.red,
    ),
  ),
)
Copy the code

How do I get the properties of a StatefulWidget control in the State class

class Test extends StatefulWidget {
  Test({this.data});
  final int data;
  @override
  State<StatefulWidget> createState() => _TestState();
}

class _TestState extends State<Test>{}Copy the code

Teststate = testState; testState = testState;

  1. Define the same parameter in _TestState, which is cumbersome and not recommended.
  2. Direct use ofwidget.data(Recommended).

default value of optional parameter must be constant

The above exception is often encountered in class constructors, as shown in the following code:

class BarrageItem extends StatefulWidget {
  BarrageItem(
      { this.text,
      this.duration = Duration(seconds: 3)});
Copy the code

Exception message: The optional parameter must be constant. Modify it as follows:

const Duration _kDuration = Duration(seconds: 3);

class BarrageItem extends StatefulWidget {
  BarrageItem(
      {this.text,
      this.duration = _kDuration});
Copy the code

Dart constants usually start with k, _ means private, and can only be used within the current package. Don’t ask me why.

How do I remove the Debug icon in the upper right corner in debug mode

MaterialApp(
 debugShowCheckedModeBanner: false
)
Copy the code

How do I use hexadecimal color values

The following uses do not display colors:

Color(0xb74093)
Copy the code

The Color constructor is ARGB, so we need to add transparency.

Color(0xFFb74093)
Copy the code

FF stands for completely opaque.

How do I change the icon and name of my application

Link: blog.csdn.net/mengks1987/…

How do I set the initial value for TextField

class _FooState extends State<Foo> {
  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController(text: 'Initial value');
  }

  @override
  Widget build(BuildContext context) {
    returnTextField( controller: _controller, ); }}Copy the code

Scaffold.of() called with a context that does not contain a Scaffold

Scaffold.of() context is not contained in scaffold.of ().

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('the old meng'),
      ),
      body: Center(
        child: RaisedButton(
          color: Colors.pink,
          textColor: Colors.white,
          onPressed: _displaySnackBar(context),
          child: Text('show SnackBar'),),),); } } _displaySnackBar(BuildContext context) {final snackBar = SnackBar(content: Text('the old meng'));
  Scaffold.of(context).showSnackBar(snackBar);
}
Copy the code

Note that the context of a HomePage is not contained in that Scaffold. This Scaffold does not call the HomePage. The context is changed as follows:

_scaffoldKey.currentState.showSnackBar(snackbar); 
Copy the code

Or:

Scaffold(
    appBar: AppBar(
        title: Text('the old meng'),
    ),
    body: Builder(
        builder: (context) => 
            Center(
            child: RaisedButton(
            color: Colors.pink,
            textColor: Colors.white,
            onPressed: () => _displaySnackBar(context),
            child: Text('the old meng'(), ((), ((), ((), ((), (()Copy the code

Waiting for another flutter command to release the startup lock

This problem is often encountered when executing flutter commands.

Solution 1:

1. Run the following command on the terminal for Mac or Linux:

killall -9 dart
Copy the code

2, Window run the following command:

taskkill /F /IM dart.exe
Copy the code

Solution 2:

Delete the /bin/cache/lockfile file in the flutter SDK directory.

Can’t callsetState

It cannot be called in the StatelessWidget control and needs to be called in the StatefulWidget.

Sets the percentage of the current control size to the parent control size

1. Use the FractionallySizedBox control

Get the size of the parent control and multiply it by the percentage:

MediaQuery.of(context).size.width * 0.5
Copy the code

Row wraps TextField exception directly: BoxConstraints Forces an infinite width

Solutions:

Row(
	children: <Widget>[
		Flexible(
			child: new TextField(),
		),
  ],
),
Copy the code

TextField gets focus and loses focus dynamically

Get focus:

FocusScope.of(context).requestFocus(_focusNode);
Copy the code

_focusNode is the focusNode of TextField:

_focusNode = FocusNode();

TextField(
	focusNode: _focusNode,
	...
)
Copy the code

Lose focus:

_focusNode.unfocus();
Copy the code

How to determine the current platform

import 'dart:io' show Platform;

if (Platform.isAndroid) {
  // Android-specific code
} else if (Platform.isIOS) {
  // iOS-specific code
}
Copy the code

Platform types include:

Platform.isAndroid
Platform.isFuchsia
Platform.isIOS
Platform.isLinux
Platform.isMacOS
Platform.isWindows
Copy the code

Android cannot access HTTP

This is not a problem with Flutter per se, but is often encountered in development. HTTP access is disabled by default on Android Pie and above and IOS, mainly for security reasons.

Android solution:

In the. / android/app/SRC/main/AndroidManifest. Application tag in the XML configuration files inside set networkSecurityConfig properties:

<? The XML version = "1.0" encoding = "utf-8"? > <manifest ... > <application android:networkSecurityConfig="@xml/network_security_config"> <! -... --> </application> </manifest>Copy the code

In. / android/app/SRC/main/res directory to create XML folder (existing need not create), create network_security_config in XML folder. The XML file, the content is as follows:

<? The XML version = "1.0" encoding = "utf-8"? > <network-security-config> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" />  </trust-anchors> </base-config> </network-security-config>Copy the code

IOS cannot access HTTP

Add the following to the./ios/Runner/ info.plist file:

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE plist PUBLIC "- / / / / DTD plist Apple / 1.0 / EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd" > < plist Version = "1.0" > < dict >... <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> </dict> </plist>Copy the code

communication

Old Meng Flutter blog address (nearly 200 controls usage) : laomengit.com