flutter

Flutter bottom overflowed by 64 pixels

方案一:

如果没有ScrollView或者ListView等可滚动空间包裹,则可以通过 padding设置实现键盘不被遮挡问题

Padding(
  padding: EdgeInsets.only(
    bottom: MediaQuery.of(context).viewInsets.bottom
  ),
  child: TextField(
  )
)

MediaQuery.of(context).viewInsets.bottom 为键盘弹出时键盘高度,如果上面代码段被可滚动widget包裹,则会出现输入框并不一定在紧挨着键盘

方案二: 通过 Scaffold

Scaffold是自带自适应输入法弹出的,它有一个属性resizeToAvoidBottomInset,用来控制Scaffold组件是否需要自适应输入法弹出,重新计算view的高度,默认为 true 适应键盘模式

Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildContentView(context) //被ListView或者SingleChildScrollView等滑动控件包裹的TextField
);

_buildContentView 可以含有输入框的控件

注意:如果有自定义的APPBar控件,不配置appBar的话顶部会多一部分高度的空View

 AppBar(
        title: Text('Title'),
        centerTitle: true,
        elevation: 0,
        toolbarHeight: 0.001,
        bottom: null,

        brightness:Brightness.light ,

      )

可以设置 toolbarHeight 的高度,如果要设置状态栏的颜色则 toolbarHeight 高度不能为 0,否则 设置状态栏文字颜色的 brightness 属性就失效.
————————————————

flutter方法里展示dialog,设置setState()无效

We will see in this article how to call setstate in Alert Dialogs in Flutter. First, we will create a simple button on any screen and will open an alert dialog by clicking that button. We will use a checkbox in that dialog and will try to change his state by using the setstate.

Let’s move to our topic:

Create a simple Stateful widget with DialogButton or whatever that you want, and create a button in this screen and will add the texts ‘Open Dialog’ in that button.

class _DialogButtonState extends State<DialogButton> {
  @override
  Widget build(BuildContext context) {
    final double height = MediaQuery.of(context).size.height;
    final double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: const Color(0xffF2F2F2),
      body: SizedBox(
        height: height,
        width: width,
        child: Center(
          child: Container(
            height: 50.0,
            width: double.infinity,
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: ElevatedButton(
              onPressed: (){},
              child: const Center(
                child: Text("Open Dialog",
                style: TextStyle(
                  fontSize: 20.0,
                ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

The output should be like this:

Now, when we click on the button then an alert dialog will occur. So, for that we will write the code in the way:

final bool _isChecked = false;


Future _openDialog() => showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("SetState In Dialog"),
        content: CheckboxListTile(
          controlAffinity: ListTileControlAffinity.leading,
          title: const Text("Hello"),
          value: _isChecked,
          onChanged: (value){

          },
        ),
        actions: [
          TextButton(
              onPressed: (){
                Navigator.of(context).pop();
              },
              child: const Text("SUBMIT"),
          ),
        ],
      ),
  );

After this, we call this _openDialog() inside the button property onPressed: (){}, and the output will be like this…

But now the problem is here that when we click the checkbox in the alert dialog the alert dialog state is not changing. So, what we will do? We will wrap the AlertDialog inside the StatefulBuilder. Because when we wrap the alert dialog inside the statefulBuilder then inside statefulBuilder we can change anything easily by using the setstate…

Let’s write the code:

  Future _openDialog() => showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: const Text("SetState In Dialog"),
            content: CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              title: const Text("Hello"),
              value: _isChecked,
              onChanged: (value){
                setState(() {
                  _isChecked = value!;
                });
              },
            ),
            actions: [
              TextButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: const Text("SUBMIT"),
              ),
            ],
          );
        }
      ),
  );

we will update the _openDialog function in this way and our setState will work inside the alert dialog.

Read this article: How to make transparent appbar in Flutter

Flutter Docs:

Complete Code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Dialog with SetState',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      /*home: SplashScreen(
          isSvg: false,
          iconPath: 'assets/bg.jpg',
          onPressed: (){},
      ),*/
      //home: const Appbar(),
      home: const DialogButton(),
    );
  }
}


class DialogButton extends StatefulWidget {
  const DialogButton({Key? key}) : super(key: key);

  @override
  State<DialogButton> createState() => _DialogButtonState();
}

class _DialogButtonState extends State<DialogButton> {

  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    final double height = MediaQuery.of(context).size.height;
    final double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: const Color(0xffF2F2F2),
      body: SizedBox(
        height: height,
        width: width,
        child: Center(
          child: Container(
            height: 50.0,
            width: double.infinity,
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: ElevatedButton(
              onPressed: (){
                _openDialog();
              },
              child: const Center(
                child: Text("Open Dialog",
                style: TextStyle(
                  fontSize: 20.0,
                ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future _openDialog() => showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: const Text("SetState In Dialog"),
            content: CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              title: const Text("Hello"),
              value: _isChecked,
              onChanged: (value){
                setState(() {
                  _isChecked = value!;
                });
              },
            ),
            actions: [
              TextButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: const Text("SUBMIT"),
              ),
            ],
          );
        }
      ),
  );

}

Output:

Download

So, in this way you can call SetState in Alert DialogFlutter

Read these Articles:

Flutter – Splash Screen Custom Widget

Top 10 highest paid skills on Fiverr in 2022

Top 15 websites for free stock photos

Tags: call setstate in dialog flutterFlutter – How to call SetState in Alert DialogFlutter – How to call SetState in Alert Dialog (2022)flutter alert dialog with setstateflutter alert dialogsflutter call setstate in alert dialogFlutter Tutorials flutter skills flutter app developmenthow setstate call in alert dialoghow to call setstate in alert dialog flutterhow to call setstate inside alert dialoghow we can apply setstate inside alert dialog fluttersetstate in dialog flutter

flutter 运行项目报错:Try launching Xcode and selecting “Product > Run” to fix the prob

2020-04-08 14:45:16.875 ios-ncn[38706:203108] [ !! ] Error 0xe800007f: Device doesn't support wireless sync. AMDeviceStartService(device, CFSTR("com.apple.debugserver"), &gdbfd, NULL)
Could not install build/ios/iphoneos/Runner.app on faae62f4d8b4ee9b0c3d85dd89226e203ffcf763.
Try launching Xcode and selecting "Product > Run" to fix the problem:
  open ios/Runner.xcworkspace
Error launching application on chenfaniPhone.
复制代码
解决办法:
// 终端执行命令 
//选择flutter通道,一般都选择稳定版本stable
$ flutter channel // 之后选择“*”的分支 执行,例如flutter channcel stable 
//检测flutter环境是否正常
$ flutter doctor 
//更新flutter
$ flutter upgrade --force

Flutter解决报错Incorrect use of ParentDataWidget以及边界约束问题

Flutter解决报错Incorrect use of ParentDataWidget以及边界约束问题

报错信息如下:
在这里插入图片描述
关于这种报错怎么看呢?
1
1处告诉我们这个错误跟父组件有关,然后看到2处,就能分析出在加载自己写的HomePage这个页面时,该页面下的Column->Container->ConstrainedBox->Expanded->ConstrainedBox这个路径下的子组件出现了问题。
解决方案是把Expanded这个控件给撤了,直接上ConstrainedBox。
原代码:

Container(
// width: MediaQuery.of(context).size.width,
height: 36.0,
child: Expanded(
flex: 1,
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: Stack(
alignment: AlignmentDirectional.topCenter,
children: [
Positioned(
child: Text(“为你精心推荐”,textDirection: TextDirection.ltr,style: TextStyle(fontSize: 20),),
left: 3.0,
top: 3.0,
),
Positioned(
right: 3.0,
top: 3.0,
child: Container(
child: Text(“查看更多”,textDirection: TextDirection.rtl,style: TextStyle(fontSize: 16),),
/*Padding(
padding: EdgeInsets.all(4),
child:
),*/
decoration: BoxDecoration(
border: Border.all(color: Colors.black87,width: 1.0,style: BorderStyle.solid),
borderRadius: BorderRadius.circular(20)
),
)
)
],
),
),
),
)

修改后的代码:

Container(
// width: MediaQuery.of(context).size.width,
height: 36.0,
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: Stack(
alignment: AlignmentDirectional.topCenter,
children: [
Positioned(
child: Text(“为你精心推荐”,textDirection: TextDirection.ltr,style: TextStyle(fontSize: 20),),
left: 3.0,
top: 3.0,
),
Positioned(
right: 3.0,
top: 3.0,
child: Container(
child: Text(“查看更多”,textDirection: TextDirection.rtl,style: TextStyle(fontSize: 16),),
/*Padding(
padding: EdgeInsets.all(4),
child:
),*/
decoration: BoxDecoration(
border: Border.all(color: Colors.black87,width: 1.0,style: BorderStyle.solid),
borderRadius: BorderRadius.circular(20)
),
)
)
],
),
)
)

为什么这样修改就对了?
经过各种百度搜索,发现Flutter 中的 widget 由在其底层的 RenderBox 对象渲染而成。渲染框由其父级 widget 给出约束,并根据这些约束调整自身尺寸大小。约束是由最小宽度、最大宽度、最小高度、最大高度四个方面构成;尺寸大小则由特定的宽度和高度两个方面构成。
具体的可参照

https://chenglu.blog.csdn.net/article/details/102481814
————————————————
版权声明:本文为CSDN博主「记录每一次进步」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_46411441/article/details/117604705

How to Use InputFormatter on Flutter TextField?

When the form has a multiple TextField Widget in it each TextField accept an only certain type of values in a certain format. To make TextField accept only certain types of InputFormatter is used.

How to Use InputFormatter on Flutter TextField?

Formatters

It already has implementations, which are FilteringTextInputFormatter (formerly BlacklistingTextInputFormatter and WhitelistingTextInputFormatter) and LengthLimitingTextInputFormatter.

If you want to implement your own formatter, you can do so by extending TextInputFormatter itself and implementing formatEditUpdate in there.

For this we are going to use the FilteringTextInputFormatter.deny constructor:

TextField(
inputFormatters: [
FilteringTextInputFormatter.deny(RegExp(r‘[/\\]’)),
],
)

There are also already included static properties in the FilteringTextInputFormatter class: one of these is FilteringTextInputFormatter.digitsOnly.
It will only accept/allow digits and is equivalent to an .allow(RegExp(‘[0-9]’)) formatter.

Now you can use FilteringTextInputFormatter to do InputFormatter on TextField Widget or TextFormField.

inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r‘^ ?\d*’)),]
inputFormatters: [FilteringTextInputFormatter.deny(‘ ‘)]
inputFormatters: [FilteringTextInputFormatter.digitsOnly]

For e.x

TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly
],
),

Other options:

  • lowercase letters: a-z
  • capital letters: A-Z
  • lowercase vowels accented: á-ú
  • capital vowels accented: Á-Ú
  • numbers: 0-9
  • space : (space)

Note: the spacings are to explain better.

inputFormatters: [
WhitelistingTextInputFormatter(RegExp(“[a-z A-Z á-ú Á-Ú 0-9]”))
]

Conclusion:

In this article, We have been through How to Use InputFormatter on Flutter TextField?

Thanks for Reading!!! Keep Learning.

Do let us know if you need any assistance with Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

flutter 使用MD5加密

1、在pubspec.yaml中引入crucpto,更新依赖

crypto: ^2.1.5
2、引入头文件

import ‘dart:convert’;
import ‘dart:typed_data’;
import ‘package:crypto/crypto.dart’;
3、使用md5加密

///使用md5加密
String generateMD5(String data) {
Uint8List content = new Utf8Encoder().convert(data);
Digest digest = md5.convert(content);
return digest.toString();
}
————————————————
版权声明:本文为CSDN博主「SkyCloud5+2」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lqw200931116/article/details/123040516

ElevatedButton 背景修改

You can style ElevatedButton by using the styleFrom static method or the ButtonStyle class. The first one is more convenience than the second one.

Using styleFrom to style an ElevatedButton:

ElevatedButton(
      child: Text('Button'),
      onPressed: () {},
      style: ElevatedButton.styleFrom({
           Color primary, // set the background color 
           Color onPrimary, 
           Color onSurface, 
           Color shadowColor, 
           double elevation, 
           TextStyle textStyle, 
           EdgeInsetsGeometry padding, 
           Size minimumSize, 
           BorderSide side, 
           OutlinedBorder shape, 
           MouseCursor enabledMouseCursor, 
           MouseCursor disabledMouseCursor, 
           VisualDensity visualDensity, 
           MaterialTapTargetSize tapTargetSize, 
           Duration animationDuration, 
           bool enableFeedback
     }),
),