flutter零散知识点记录

1.页面跳转传递的参数如何接收

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.自定义组件中定义函数获取Provide值, 如下所示,会报错
在这里插入图片描述
在这里插入图片描述

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

3.手机号正则校验

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:字符串replace相关的方法
参考该文章

5.给Container添加边框

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

6.按钮样式调整

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.更改OulinedButton圆角和边框

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.去除button的padding

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

9.TextSpan可点击操作

/// 注意两个点不是写错哦
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设置总体背景色(待确认)

main.dart中:

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

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

11.弹窗

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.解决type ‘List’ is not a subtype of type 'List’错误

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

13.TextField设置为只读

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

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

14.map数组如何获取索引值

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

15.项目中应用Provider

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.设置TextField像web的textarea一样, 随着内容高度变化而变化

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

17.TextField去掉下划线

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

18.执行转JSON命令

flutter packages pub run build_runner build

19.获取手机顶部黑条高度

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

20.页面底部固定图片, 如何在弹窗弹出的时候不会被一起顶上去

Scaffold(
	resizeToAvoidBottomInset: false
)

猜你喜欢

转载自blog.csdn.net/u013558749/article/details/120171249