美文网首页
flutter的一些tips

flutter的一些tips

作者: smallLabel | 来源:发表于2019-11-15 10:07 被阅读0次
    1. dio忽略HTTPS
    Dio dio = Dio(options);
        (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
            client.badCertificateCallback=(X509Certificate cert, String host, int port){
    //          if(cert.pem==PEM){ // Verify the certificate
    //            return true;
    //          }
              return true;
            };
          };
    
    1. dio cookie获取
    // 引入 dio_cookie_manager: 1.0.0
    import 'package:dio_cookie_manager/dio_cookie_manager.dart';
    import 'package:cookie_jar/cookie_jar.dart';
    
    var cookieJar = CookieJar();
    dio.interceptors.add(CookieManager(cookieJar));
    Response res = await dio.post(URL_Login, data: {'userid': 'liuxun2 ', 'password': rsapw, 'systemCode': 'A08'});
    print(cookieJar.loadForRequest(Uri.parse(URL_Login)));
    
    1. flutter用vscode时控制台日志输出不完整
      不清楚什么原因,不过可以在dart Devtools上查看完整log。怎么打开dart DevTools另行百度。


      1574132472220.jpg
    1. multi_image_picker插件在iOS上的使用,版本4.5.9
      问题描述:添加这个插件后莫名其妙的编译不通过了
      解决方法: 参考这个
      因为默认工程就是用swift的,所以我仅仅只是添加权限,删除podfile.lock和pods文件夹,重新pod install,在podfile里最下面的代码添加
    post_install do |installer|
      installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
          config.build_settings['ENABLE_BITCODE'] = 'NO'
          config.build_settings['SWIFT_VERSION'] = '5.0'
        end
      end
    end
    
    1. 可滚动页面嵌套ListView
      可滚动页面CustomScrollView在嵌套其他的widget时,必须使用Sliver组件,其他的组件可以采用SliverToBoxAdapter将其包裹。以下为示例代码,数据都是写死的
    Expanded(
                  child:  CustomScrollView(
                   slivers: <Widget>[
                     SliverToBoxAdapter(
                       child: Container(
                         color: Colors.white,
                         child: PlanDetailHeader(title: '测试巡场', time: '12:00', pinlv: '每日', type: '限时', desc: '说明', status: kNoStart,),
                       )
                     ),
                     SliverToBoxAdapter(
                       child: Container(
                         margin: EdgeInsets.symmetric(vertical: 12),
                         height: 42,
                         color: Colors.white,
                         child: InkWell(
                           onTap: (){
                             NavigatorUtils.getProblemDetailPage(context);
                           },
                           child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(left: 12),
                                child: Text('关联问题:2', style:TextStyle(color: Color(0xFF222222), fontSize: 16, fontWeight: FontWeight.bold)),
                              ),
                              Container(
                                margin: EdgeInsets.only(right: 12),
                                child: Center(child: Text('>', style: TextStyle(color: Color(0xFF222222), fontWeight: FontWeight.bold)),),
                                width: 20,
                                height: 20,
                                decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(color: Color(0xFF222222), width: 2)
                                ),
                              )
                            ],
                          ),
                         )
                       ),
                     ),
                     SliverToBoxAdapter(
                       child: Container(
                         height: 42,
                         color: Colors.white,
                         child: InkWell(
                           onTap: (){print('完成进度被点击');},
                           child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(left: 12),
                                child: Text('完成进度:1/2', style:TextStyle(color: Color(0xFF222222), fontSize: 16, fontWeight: FontWeight.bold)),
                              ),
                              Container(
                                margin: EdgeInsets.only(right: 12),
                                child: Center(child: Text('>', style: TextStyle(color: Color(0xFF222222), fontWeight: FontWeight.bold)),),
                                width: 20,
                                height: 20,
                                decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(color: Color(0xFF222222), width: 2)
                                ),
                              )
                            ],
                          ),
                         )
                       ),
                     ),
                     SliverToBoxAdapter(
                       child: Container(
                         color: Colors.white,
                         margin: EdgeInsets.only(top: 12),
                         padding: EdgeInsets.only(left: 12, top: 16, bottom: 16),
                         child: Column(
                           crossAxisAlignment: CrossAxisAlignment.start,
                           children: <Widget>[
                             Text('评论', style:TextStyle(color: Color(0xFF222222), fontSize: 16, fontWeight: FontWeight.bold)),
                             Divider(
                               height: 2,
                               color: Color(0xFFF7F7F7),
                             )
                           ],
                         )
                       ),
                     ),
                     // 评论列表
                    SliverList(
                      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                          return Container(
                            height: 60,
                            color: Colors.white,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text('测试数据'),
                                Divider()
                              ],
                            ),
                            padding: EdgeInsets.only(left: 12),
                          );
                      },
                      childCount: 30
                      ),
                    )
                   ],
                 ),
                ),
    

    效果图如下:


    带有头部的列表
    1. scrollview嵌套ListView自动撑开,解决ListView因为没有设置高度的报错问题
      Vertical viewport was given unbounded height.
      解决办法:设置ListView的shrinkWraptrue,同时设置physics属性为ScrollPhysics()
      示例代码如下:
    import 'package:flutter/material.dart';
    import 'package:multi_image_picker/multi_image_picker.dart';
    import '../../utils/color_util.dart';
    import '../../utils/const_value.dart';
    
    class ProblemDetailPage extends StatefulWidget {
      ProblemDetailPage({Key key}) : super(key: key);
    
      @override
      _ProblemDetailPageState createState() => _ProblemDetailPageState();
    }
    
    class _ProblemDetailPageState extends State<ProblemDetailPage> {
    
    List<Widget> _bottomButton(String status) {
        // 根据计划状态设置底部按钮内容
        List<String> buttonContents;
        List<Color> colors = [Color(0xFF74CCA0), Color(0xFF10B2A3), Color(0xFF2D63DD),];
        if (status == kUnconfirm) {
          buttonContents = ['添加评论','位置查看', '确认接收'];
        } else if (status == kResilving) {
          buttonContents = ['添加评论','位置查看'];
        } else if (status == kResolved) {
          buttonContents = ['添加评论', '位置查看'];
        } 
        List<Widget> _buttons = [];
        for (var i = 0; i < buttonContents.length; i++) {
          String content = buttonContents[i];
          Color color = colors[i];
          Expanded expand = Expanded(
              flex: 1,
              child: InkWell(
              child: Container(
                child: Center( 
                  child: Text(content, style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),)
                ),
                color: color,
                padding: EdgeInsets.symmetric(vertical: 12),
              ),
              onTap: (){print('按钮被按下');},
              borderRadius: BorderRadius.all(Radius.circular(0)),
            )
          );
          
          _buttons.add(expand);
        }
      
        return _buttons;
      }
      List<Asset> images = [];
      Widget _buildGridView() {
       
       
        GridView gridview = GridView.count(
          shrinkWrap: true,
          padding: EdgeInsets.symmetric(horizontal: 12),
          crossAxisCount: 3,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
          physics: ScrollPhysics(),
          children: List.generate(images.length + 1 , (int index) {
            if (index != images.length) {
              Asset asset = images[index];
              return Stack(
                alignment: Alignment.center,
                children: <Widget>[
                      ClipRRect(
                      child: AssetThumb(
                      width: 109,
                      height: 109,
                      asset: asset,
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  Positioned(
                    right: 12,
                    top: 12,
                    child: InkWell(
                      onTap: (){
                        setState(() {
                          images.removeAt(index);
                        });
                      },
                      child: Container(
                        padding: EdgeInsets.all(0),
                        child: Center(child: Text('X', style: TextStyle(color: Colors.white),),),
                        width: 16,
                        height: 16,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Color(0xab000000)
                        ),
                      ),
                    )
                  )
                ],
              );
            } else {
              Widget container = InkWell(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                      color: Color(0xFF9EA3B7),
                      width: 0.5
                    )
                  ),
                  height: 109,
                  width: 109,
                  child: Center(
                    child: Image.asset('assets/xiangji.png'),
                  ),
                ),
                onTap: getImages,
              );
              return container;
            }
          }),
        );
        return gridview;
      }
      // 获取图片
      Future<void> getImages() async {
        List<Asset> result = [];
        String error = 'no error';
    
        try {
          result = await MultiImagePicker.pickImages(
            maxImages: 5,
            enableCamera: true,
            selectedAssets: images,
            cupertinoOptions: CupertinoOptions(takePhotoIcon: 'chat'),
            materialOptions: MaterialOptions(
              actionBarColor: '#abcdef',
              actionBarTitle: '照片',
              allViewTitle: 'all photos',
              useDetailsView: false,
              selectCircleStrokeColor: '#000000'
            )
          );
    
          for (var r in result) {
            var t = await r.filePath;
            print(t);
          }
    
        } on Exception catch(e) {
          error = e.toString();
        }
        setState(() {
          for (Asset asset in result) {
            images.insert(0, asset);
          }
        });
    
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('问题详情'),
          ),
          body: Container(
            color: ColorUtil.backgroundColor,
            child: SafeArea(
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: CustomScrollView(
                      slivers: <Widget>[
                        SliverToBoxAdapter(
                          child: Container(
                            color: Colors.white,
                            child: ProblemDetailHeader(),
                          ),
                        ),
                        SliverToBoxAdapter(
                          child: Container(
                            margin: EdgeInsets.only(top: 12),
                            color: Colors.white,
                            padding: EdgeInsets.all(12),
                            child: Column(
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Text('总经办巡场计划', style: TextStyle(color: Color(0xFF222222), fontSize: 16, fontWeight: FontWeight.bold),),
                                    Container(
                                      margin: EdgeInsets.only(right: 12),
                                      child: Center(child: Text('>', style: TextStyle(color: Color(0xFF222222), fontWeight: FontWeight.bold)),),
                                      width: 20,
                                      height: 20,
                                      decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      border: Border.all(color: Color(0xFF222222), width: 2)
                                      ),
                                    )
                                  ],
                                ),
                                Container(
                                  margin: EdgeInsets.symmetric(vertical: 12),
                                  height: 2,
                                  color: ColorUtil.dividerColor,
                                ),
                                Container(
                                  margin: EdgeInsets.only(bottom: 7),
                                  child: Align(
                                    alignment: Alignment.centerLeft,
                                    child: Text('外广场', style: TextStyle(color: Color(0xFF333333), fontSize: 12, )),
                                  )
                                ),
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text('检查项检查项检查项检查项检查项检查项检查项检查项检查项检查项检', style: TextStyle(color: Color(0xFF666666), fontSize: 12)),
                                )
                              ],
                            ),
                          ),
                        ),
                        SliverToBoxAdapter(
                          child: Container(
                            margin: EdgeInsets.only(top: 12),
                            color: Colors.white,
                            padding: EdgeInsets.all(12),
                            child: Column(
                              children: <Widget>[
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text('总经办巡场计划', style: TextStyle(color: Color(0xFF222222), fontSize: 16, fontWeight: FontWeight.bold),),
                                ),
                                Container(
                                  margin: EdgeInsets.symmetric(vertical: 12),
                                  height: 2,
                                  color: ColorUtil.dividerColor,
                                ),
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text('检查项检查项检查项检查项检查项检查项检查项检查项检查miaoshu sdhkfjhsakjhfksahdfkasjhfkasjhfkasjghkdjhgksje项检查项检', style: TextStyle(color: Color(0xFF666666), fontSize: 12)),
                                )
                              ],
                            ),
                          ),
                        ),
                        SliverToBoxAdapter(
                          child: Container(
                            color: Colors.white,
                            margin: EdgeInsets.only(top: 12),
                            child: Column(
                               children: <Widget>[
                                 Container(
                                  margin: EdgeInsets.only(bottom: 12, left: 12, top: 12),
                                  child: Align(
                                    alignment: Alignment.centerLeft,
                                    child: Text('问题描述', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                                  )
                                ),
    
                               Container(
                                 child: _buildGridView(),
                               )
                                
                               ],
                            ),
                          ),
                        ),
                        SliverToBoxAdapter(
                          child: Container(
                            margin: EdgeInsets.only(top: 12),
                            padding: EdgeInsets.only(left: 12, right: 12),
                            color: Colors.white,
                            child: Column(
                              children: <Widget>[
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text('评论', style: TextStyle(color: Color(0xFF222222), fontSize: 16, fontWeight: FontWeight.bold)),
                                ),
                                Divider(),
                                ListView.builder(
                                  physics: ScrollPhysics(),
                                  itemBuilder: (BuildContext context, int index) {
                                    return Container(
                                              height: 50,
                                              color: Colors.white,
                                              child: Center(child:Text('测试数据', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),),),
                                            );
                                  },
                                  itemCount: 30,
                                  shrinkWrap: true,
                                ),
                                
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: 49,
                    child: Flex(
                      direction: Axis.horizontal,
                      children: <Widget>[
                        Expanded(
                          child: Row(
                            children: _bottomButton(kUnconfirm),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
          ),
          )
        );
      }
    }
    
    
    // 问题详情头部
    class ProblemDetailHeader extends StatefulWidget {
      ProblemDetailHeader({Key key}) : super(key: key);
    
      @override
      _ProblemDetailHeaderState createState() => _ProblemDetailHeaderState();
    }
    
    class _ProblemDetailHeaderState extends State<ProblemDetailHeader> {
      @override
      Widget build(BuildContext context) {
        return Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 12, top: 12, right: 12),
                width: MediaQuery.of(context).size.width,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text('店铺商品摆放凌乱', style: TextStyle(fontSize: 16, color: Color(0xFF333333), fontWeight: FontWeight.bold)),
                    Text('未确认', style: TextStyle(fontSize: 12, color: Color(0xFF2D63DD), fontWeight: FontWeight.bold),)
                  ],
                ),
              ),
              Container(
                height: 2,
                margin: EdgeInsets.only(left: 12, top: 12, right: 12),
                color: ColorUtil.dividerColor,
              ),// 分割线
              Column(
                children: <Widget>[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                      margin: EdgeInsets.only(left: 12, top: 12, right: 12),
                      child: Text('问题类型:一般问题', style: TextStyle(color: ColorUtil.textGrayColor, fontSize: 12),),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                      margin: EdgeInsets.only(left: 12, top: 12, right: 12, bottom: 12),
                      child: Text('提报时间:12:00', style: TextStyle(color: ColorUtil.textGrayColor, fontSize: 12),),
                    )
                  )
                ],
              ),
            ],
          );
      }
    }
    

    代码中使用了图片多选框架multi_image_picker: ^4.5.9

    1. 原生iOS集成flutter ,我的flutter版本是1.9.1+hotfix.6, xcode 11.1
      最好参考官方集成说明,因为不同的版本集成步骤可能有些微差别,我也是先搜索网上,发现版本有点旧,所以直接照着官方说明操作。
      基础步骤没有太大差别,以下简要说明下,以官方为准。
    • 安装cocoapods,这个请自行百度
    • 关闭bitcode
    • 在终端cd到你的iOS程序同级目录下,执行命令flutter create -t module my_flutter(my_flutter为新建的flutter工程名字,随意取),执行完成后可在目录下看到my_flutter文件夹,如图
      my_flutter
    • 在Podfile中添加以下代码
      flutter_application_path = 'path/to/my_flutter/'    
      load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
    

    flutter_application_path就是你新建的my_flutter的路径
    在target中添加

      target 'MyApp' do
        install_all_flutter_pods(flutter_application_path)
      end
      target 'MyAppTests' do
        install_all_flutter_pods(flutter_application_path)
      end
    
    • 执行pod install命令
    1. vscode中flutter代码格式化方法
      mac下快捷键shift+option+f
      windows下快捷键shift+alt+f

    相关文章

      网友评论

          本文标题:flutter的一些tips

          本文链接:https://www.haomeiwen.com/subject/hsyjictx.html