Flutter scattered knowledge point records

1. How to receive parameters passed by page jump

Map<String, dynamic> argument =
  ModalRoute.of(context).settings.arguments as Map<String, dynamic>;
  int id;
  if (argument != null) {
    id = argument['id'];
  }

/// 如果直接在InitState中获取会报错,处理方案如下
Future.delayed(Duration.zero, () {
      setState(() {
       ModalRoute.of(context).settings.arguments as Map<String, dynamic>;
	  int id;
	  if (argument != null) {
	    id= argument['id'];

        /// 根据传递过来的参数发起请求
        _getXXX(id);
      });
    });

2. Define a function in the custom component to obtain the Provide value, as shown below, an error will be reported
Insert image description here
Insert image description here

/// 按照错误提示纠正写法
Provider.of<LoginView>(context, listen: false).userId

3. Mobile phone number regular verification

RegExp exp = RegExp(
          r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
bool matched = exp.hasMatch(mobileTextController.text);

4.dart: For methods related to string replacement,
please refer to this article.

5. Add a border to the Container

Container(
	decoration: BoxDecoration(
	    border: Border(
	   bottom: BorderSide(width: 1, color: coloreee),
	 )),
	 child: ...
)

6.Button style adjustment

ElevatedButton(
   onPressed: () {
      print('完成');
      // Navigator.pushNamed(context, 'inCounselByTw', arguments: {"page": 'ing'});
    },
    style: ButtonStyle(
        elevation: MaterialStateProperty.all(0),
        backgroundColor:
        MaterialStateProperty.resolveWith(
                (states) {
              //设置按下时的背景颜色
              if (states
                  .contains(MaterialState.pressed)) {
                return ThemeColors.bgColor;
              }
              //默认不使用背景颜色
              return ThemeColors.bgColor;
            }),
        shape: MaterialStateProperty.all(
            StadiumBorder()),
        minimumSize:
        MaterialStateProperty.all(Size(104, 32))),

7.Change OulinedButton rounded corners and borders

OutlinedButton(
      onPressed: (){},
      style: OutlinedButton.styleFrom(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(18.0),
        ),
        side: BorderSide(width: 1, color: ThemeColors.zxzxtipColor),
      ),
      child: Text('医生主页',
        style: TextStyle(
          fontSize: 12,
          color: ThemeColors.zxzxtipColor
        ),
      )
    )

8. Remove button padding

tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: MaterialStateProperty.all(Size(0, 0)),
padding: MaterialStateProperty.all(EdgeInsets.zero),

9.TextSpan can be clicked

/// 注意两个点不是写错哦
import 'package:flutter/gestures.dart';

TextSpan(
     text: "点我变色",
     style: TextStyle(fontSize: 20.0,color: flag ? Colors.red : Colors.blue),
     recognizer: tapGestureRecognizer..onTap = (){
       setState(() {
         flag = !flag;
       });
     },
   )

10.Flutter sets the overall background color (to be confirmed)

main.dart中:

return new MaterialApp(
	title: '标题',
	home: Scaffold(
		backgroundColor: Colors.white
	)
)

/// 如果需要为某个页面单独设置一个背景色的话
Scaffold(
	backgroundColor: Colors.blue
)

11. Pop-up window

1. 底部弹窗
showModalBottomSheet

2.全屏弹窗
showDialog(
      context: context,
       builder: (BuildContext context) {
         return InkWell(
           onTap: () {
             Navigator.pop(context);
           },
           child: Container(
             width: MediaQuery.of(context).size.width,
             height: MediaQuery.of(context).size.height,
             color: Colors.white,
             child: ChooseListItem( /// 自定义组件
               callback: (val) {
                 widget.handleDepartment(val);
               },
             ),
           ),
         );
       }
   );

12. Solve the error type 'List' is not a subtype of type 'List'

/// map后加上<Widget>
Wrap(
  children:item['casts'].map<Widget>((casts){
  return Text('data');
  }).toList(),
)

13.TextField is set to read-only

TextField(
  enableInteractiveSelection: false,
  onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); },
)

//以下写法为不可编辑并且无法响应点击事件
TextField(
 enable: false,
)

14.How to get the index value of map array

timeList.asMap().entries.map<Widget>((entry){
   return time(entry.value, 'am', entry.key);
 }).toList(),

15. Apply Provider in the project

1. main.dart中引入
import 'package:tyt/provider/disease.dart';
。。。。。。dissease.dart内容。。。。。:
import 'package:flutter/material.dart';

class SetDiease extends ChangeNotifier {
  String _diease;
  String get diease => _diease ?? null;
  void setInfo(diease) {
    _diease = diease;
    notifyListeners();
  }
}
。。。。。。dissease.dart内容。。。。。:
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //异步初始化SP文件
  await SpUtil.getInstance();
  // runApp(MyApp());
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (context) => SetDiease()),
    ],
    child: MyApp(),
  ));
}

2.设置值
context.read<SetDiease>().setInfo(item); 
或者 
Provider.of<SetDiease>(context, listen: false).setInfo(item);

3.获取值
context.watch<SetDiease>().diease

16. Set the TextField like a web textarea, changing as the content height changes.

TextField(
    controller: _diseaseDesc,
     maxLines: null,
     keyboardType: TextInputType.multiline,
     style: TextStyle(
         color: ThemeColors.color999, fontSize: 18.sp
     )
   ),
// 如果需要初始的高度就设置maxLine: 数值

17.TextField removes underline

TextField(
  decoration: InputDecoration(
    border: InputBorder.none,
  ),
)

18. Execute the JSON conversion command

flutter packages pub run build_runner build

19. Get the height of the black bar at the top of the phone

import 'package:flutter_screenutil/flutter_screenutil.dart';
利用flutter-screenutil
ScreenUtil().statusBarHeight

20. How to fix the image at the bottom of the page so that it will not be pushed up when the pop-up window pops up.

Scaffold(
	resizeToAvoidBottomInset: false
)

Guess you like

Origin blog.csdn.net/u013558749/article/details/120171249