RFlutter_Alert-如何验证和返回TextFormField

时间:2020-06-01 04:12:11

标签: flutter

我在整个应用程序中都使用rflutter_alert,现在我需要了解用户提出请求的原因。因此,我从rflutter_alert页面上的示例开始,并提供了以下代码。

我无法通过验证,也无法输入用于Web服务的值。

不确定我的代码是否有小问题,或者我做错了什么。

有什么想法吗?谢谢。

Future<bool> saveRequest({context, int rId}) {
  String _reason = '';
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController reasonController = TextEditingController();

  TextStyle _style = TextStyle(
      fontFamily: 'Montserrat', fontSize: 18.0, fontWeight: FontWeight.normal);

  InputDecoration _textFormFieldDecoration({String hintText, double padding}) =>
      InputDecoration(
        //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
        contentPadding: EdgeInsets.all(padding),
        isDense: true,
        hintText: hintText,
        hintStyle: TextStyle(color: kHintText),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
      );

  return Alert(
    context: context,
    title: 'New Request',
    //desc: 'Reason',
    content: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 20.0),
        Text('Reason', textAlign: TextAlign.left, style: _style),
        SizedBox(height: 10.0),
        TextFormField(
          validator: (value) {
            if (value.isEmpty) {
              return "please enter reason";
            }
            return null;
          },
          onSaved: (value) {
            _reason = value;
          },
          decoration: _textFormFieldDecoration(
            hintText: 'reason for request',
            padding: 8.0,
          ),
          controller: reasonController,
        ),
        SizedBox(height: 10.0),
      ],
    ),
    buttons: [
      DialogButton(
        child:
            Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () async {
          if (_formKey.currentState.validate()) {
            _formKey.currentState.save();
            var saved = await doSaveRequest(pReason: _reason);
            Navigator.pop(context, false);
            if (saved.savedOK) {
              Navigator.of(context).pop();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UserRequests(
                    rId: rId,
                  ),
                ),
              );
            } else {
              Navigator.pop(context, false);
            }
          }
        },
      ),
      DialogButton(
        child:
            Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () {
          Navigator.pop(context, false);
        },
      ),
    ],
  ).show();
}

1 个答案:

答案 0 :(得分:1)

您可以在下面复制粘贴运行完整代码
您可以使用Form包装内容并提供key
代码段

content: Form(
        key: _formKey,
        child: Column(

工作演示

enter image description here

输出

I/flutter (11913): abc

完整代码

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Color kMainColor = Colors.blue;
  Color kHintText = Colors.blue;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<bool> saveRequest({context, int rId}) {
    String _reason = '';
    GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    TextEditingController reasonController = TextEditingController();

    TextStyle _style = TextStyle(
        fontFamily: 'Montserrat',
        fontSize: 18.0,
        fontWeight: FontWeight.normal);

    InputDecoration _textFormFieldDecoration(
            {String hintText, double padding}) =>
        InputDecoration(
          //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
          contentPadding: EdgeInsets.all(padding),
          isDense: true,
          hintText: hintText,
          hintStyle: TextStyle(color: kHintText),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
        );

    return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(height: 20.0),
            Text('Reason', textAlign: TextAlign.left, style: _style),
            SizedBox(height: 10.0),
            TextFormField(
              validator: (value) {
                if (value.isEmpty) {
                  return "please enter reason";
                }
                return null;
              },
              onSaved: (value) {
                _reason = value;
              },
              decoration: _textFormFieldDecoration(
                hintText: 'reason for request',
                padding: 8.0,
              ),
              controller: reasonController,
            ),
            SizedBox(height: 10.0),
          ],
        ),
      ),
      buttons: [
        DialogButton(
          child:
              Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              print(_reason);

              //var saved = await doSaveRequest(pReason: _reason);
              Navigator.pop(context, false);
              /*if (saved.savedOK) {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => UserRequests(
                      rId: rId,
                    ),
                  ),
                );
              } else {
                Navigator.pop(context, false);
              }*/
            }
          },
        ),
        DialogButton(
          child: Text('Cancel',
              style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
      ],
    ).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Basic Alert'),
              onPressed: () => saveRequest(context: context, rId: 123),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}