Flutter Q&A

These are from stackoverflow and has been tested.

1. How to change package name in flutter?

Change the package name in your AndroidManifest.xml file:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="your.package.name">
1
2

Also in your build.gradle file inside app folder

    defaultConfig {
        applicationId "your.package.name"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
1
2
3
4
5
6
7
8

Finally, change the package in your MainActivity.java class

        package your.package.name;

        import android.os.Bundle;
        import io.flutter.app.FlutterActivity;
        import io.flutter.plugins.GeneratedPluginRegistrant;
        public class MainActivity extends FlutterActivity {
1
2
3
4
5
6

2. How to making phone call from flutter

import 'package:url_launcher/url_launcher.dart'

UrlLauncher.launch("tel://21213123123")
1
2
3

3. Display SnackBar

The simplest solution is to change the home line in your MyApp widget to:

home: new Scaffold(body: new MyHomePage()),

...and then remove all mention of _scaffoldKey and instead use Scaffold.of(context) where you currently have _scaffoldKey.currentState.

4.Builder versus GlobalKey

When to use GlobalKey then?

Well, if you can, never. Try to instead use things such as context.ancestorStateOfType or context.inheritWidgetOfExtactType. You may also want to consider creating a custom RenderObject for a specific layout. RenderObject combined with parentData may also be what you want if you need a relationship between parent/children

see: https://stackoverflow.com/questions/51329065/builder-versus-globalkey

5.Flutter如何强制竖屏

void main(){
  ///
  /// 强制竖屏
  /// 
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);

  runApp(new MyApp());
}
1
2
3
4
5
6
7
8
9
10
11

在App启动的时候调用SystemChrome.setPreferredOrientations([…]) 方法。 如果想要强制横屏,则将SystemChrome.setPreferredOrientations([…]) 方法中的传参改掉即可:

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight
  ]);
1
2
3
4

6.Flutter去除右上角Debug标签

在MaterialApp初始化的时候,设置debugShowCheckedModeBanner: false

void main(){
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: new Text('My Application'),
      debugShowCheckedModeBanner: false,  // 设置这一属性即可
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new SplashScreen(),
      routes: <String, WidgetBuilder> {
          '/splashscreen': (BuildContext context) => new SplashScreen(),
          '/conditions': (BuildContext context) => new TermsAndConditionsPage(),
        },
    );
  }
}

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

How to format DateTime in Flutter

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
1
2
3
4

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

https://stackoverflow.com/questions/50214338/flutter-error-mediaquery-of-called-with-a-context-that-does-not-contain-a-med

You need a MaterialApp or a WidgetsApp arround your widget. They provide the MediaQuery. When you call .of(context) flutter will always look up the widget three to find the widget.

How to customer width of tabbar

TabBar(isScrollable: true)
1

Makes a scrollable tab bar. it's useful when your tab text context or number of your tabs doesn't fit into display size.

child: new TabBar(
            tabs: [
              new Container(
                width: 30.0,
                child: new Tab(text: 'hello'),
              ),
              new Container(
                  child: new Tab(text: 'world'),
              ),
            ],
          )

1
2
3
4
5
6
7
8
9
10
11
12

How to remove debug banner in flutter

... return new MaterialApp( title: 'Flutter Test', debugShowCheckedModeBanner: false, home: new Column( ... ), builder: (BuildContext context, Widget child) { ... } ); ...

How to Sizing elements to percentage of screen width/height

double width = MediaQuery.of(context).size.width;

double 65_width = width * 0.65;
1
2
3

Hide Android Status Bar On Flutter App

SystemChrome.setEnabledSystemUIOverlays([]) should do what you want.
1

bring back

SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values).
1

How to detect Platform

efaultTargetPlatform == TargetPlatform.iOS
          ? kIOSTheme
          : kDefaultTheme,
1
2
3

Docs: https://docs.flutter.io/flutter/dart-io/Platform-class.html

How to programatically hide widget

import "package:flutter/material.dart";

void main() {
  runApp(new ControlleApp());
}

class ControlleApp extends StatelessWidget { 
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "My App",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
  bool visibilityTag = false;
  bool visibilityObs = false;

  void _changed(bool visibility, String field) {
    setState(() {
      if (field == "tag"){
        visibilityTag = visibility;
      }
      if (field == "obs"){
        visibilityObs = visibility;
      }
    });
  }

  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(backgroundColor: new Color(0xFF26C6DA)),
      body: new ListView(
        children: <Widget>[
          new Container(
            margin: new EdgeInsets.all(20.0),
            child: new FlutterLogo(size: 100.0, colors: Colors.blue),
          ),
          new Container(
            margin: new EdgeInsets.only(left: 16.0, right: 16.0),
            child: new Column(
              children: <Widget>[
                visibilityObs ? new Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    new Expanded(
                      flex: 11,
                      child: new TextField(
                        maxLines: 1,
                        style: Theme.of(context).textTheme.title,
                        decoration: new InputDecoration(
                          labelText: "Observation",
                          isDense: true
                        ),
                      ),
                    ),
                    new Expanded(
                      flex: 1,
                      child: new IconButton(
                        color: Colors.grey[400],
                        icon: const Icon(Icons.cancel, size: 22.0,),
                        onPressed: () {
                          _changed(false, "obs");
                        },
                      ),
                    ),
                  ],
                ) : new Container(),

                visibilityTag ? new Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    new Expanded(
                      flex: 11,
                      child: new TextField(
                        maxLines: 1,
                        style: Theme.of(context).textTheme.title,
                        decoration: new InputDecoration(
                          labelText: "Tags",
                          isDense: true
                        ),
                      ),
                    ),
                    new Expanded(
                      flex: 1,
                      child: new IconButton(
                        color: Colors.grey[400],
                        icon: const Icon(Icons.cancel, size: 22.0,),
                        onPressed: () {
                          _changed(false, "tag");
                        },
                      ),
                    ),
                  ],
                ) : new Container(),
              ],
            )
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new InkWell(
                onTap: () {
                  visibilityObs ? null : _changed(true, "obs");
                },
                child: new Container(
                  margin: new EdgeInsets.only(top: 16.0),
                  child: new Column(
                    children: <Widget>[
                      new Icon(Icons.comment, color: visibilityObs ? Colors.grey[400] : Colors.grey[600]),
                      new Container(
                        margin: const EdgeInsets.only(top: 8.0),
                        child: new Text(
                          "Observation",
                          style: new TextStyle(
                            fontSize: 12.0,
                            fontWeight: FontWeight.w400,
                            color: visibilityObs ? Colors.grey[400] : Colors.grey[600],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ),
              new SizedBox(width: 24.0),
              new InkWell(
                onTap: () {
                  visibilityTag ? null : _changed(true, "tag");
                },
                child: new Container(
                  margin: new EdgeInsets.only(top: 16.0),
                  child: new Column(
                    children: <Widget>[
                      new Icon(Icons.local_offer, color: visibilityTag ? Colors.grey[400] : Colors.grey[600]),
                      new Container(
                        margin: const EdgeInsets.only(top: 8.0),
                        child: new Text(
                          "Tags",
                          style: new TextStyle(
                            fontSize: 12.0,
                            fontWeight: FontWeight.w400,
                            color: visibilityTag ? Colors.grey[400] : Colors.grey[600],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ),
            ],
          )                    
        ],
      )
    );
  }
}
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

How to make text with hint

new TextField(
  decoration: new InputDecoration.collapsed(
    hintText: 'Username'
  ),
),

new InputDecoration(
    border: InputBorder.none,
    hintText: 'Username',
  ),
),
1
2
3
4
5
6
7
8
9
10
11

How to open URL

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(new Scaffold(
    body: new Center(
      child: new RaisedButton(
        onPressed: _launchURL,
        child: new Text('Show Flutter homepage'),
      ),
    ),
  ));
}

_launchURL() async {
  const url = 'https://flutter.io';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

How to remove backbutton on appbar

appBar: new AppBar(
   title: new Text("Your Text Here"), 
   automaticallyImplyLeading: false,
),
1
2
3
4

How do I change Text Input Action Button (return/enter key) on Keyboard in Flutter?

TextField(
  textInputAction: TextInputAction.go
  ...
)
1
2
3
4

https://docs.flutter.io/flutter/services/TextInputAction-class.html#constants