Flutter Json数据转换

问题描述

我正在从用户那里获取联系信息。并通过电子邮件发送给其他人。但是我想以结构格式发送信息,例如表格等。 现在电子邮件看起来像:{“名称”:“约翰逊”,“日期”:“ 12-12-2020”,“电话”:“(387)890-0987”,“电子邮件”:“ usename @ domain。 com“}
我想以表格形式发送数据。如下所示。

1

OR

2

不喜欢 {“名称”:“约翰逊”,“日期”:“ 12-12-2020”,“电话”:“(387)890-0987”,“电子邮件”:“ usename@domain.com”}

这是我的代码

import 'dart:ui';
import 'package:Flutter/material.dart';
import 'package:Flutter/services.dart';
import 'dart:async';
import 'dart:convert';
import 'package:mailer2/mailer.dart';

void main() => runApp(new MaterialApp(home: new MyApp(),debugShowCheckedModeBanner: false,));



    class StepSixSessionSix {

      Future<Contact> createContact(Contact contact) async {
        try {
          String json = _toJson(contact);
          var options = new GmailSmtpOptions()
            ..username = 'myusername'
            ..password = 'mypassword';
          var emailTransport = new SmtpTransport(options);
          var envelope = new Envelope()
            ..from = 'email@gmail.com'
            ..recipients.add('anotheremail@outlook.com')
            ..subject = 'Testing2'
            ..html = json;

          emailTransport.send(envelope)
              .then((envelope) => print('Email sent!'))
              .catchError((e) => print('Error occurred: $e'));
        } catch (e) {
          print('Server Exception!!!');
          print(e);
          return null;
        }
      }

      String _toJson(Contact contact) {
        var mapData = new Map();

        mapData["Name"] = contact.name ;
        mapData["Phone"] = contact.phones;
        mapData["Email"] = contact.emails;
        mapData["Message Subject "] = contact.messagesubject;    // date for session 1's first
        mapData["Message Text "] = contact.messagetext;    // date for session 1's first

        String json = jsonEncode(mapData);
        return json;
      }
    }
    class Contact {
      String name;
      String phones = '';
      String emails= '';
      String messagesubject;
      String messagetext;
    }

    bool isValidPhoneNumber(String input) {
      final RegExp regex = new RegExp(r'^\(\d\d\d\)\d\d\d\-\d\d\d\d$');
      return regex.hasMatch(input);
    }

    void showMessage(String message,[MaterialColor color = Colors.red]) {
      _scaffoldKey.currentState
          .showSnackBar(new SnackBar(backgroundColor: color,content: new Text(message)));
    }

    void _submitForm() {
      final FormState form = _formKey.currentState;

      if (!form.validate()) {
        showMessage('Form is not valid!  Please review and correct.');
      } else {
        form.save(); //This invokes each onSaved event
        var stepsixsessionsix = new StepSixSessionSix();
        stepsixsessionsix.createContact(newContact);
        showMessage('Form Submitted',Colors.blue);
      }
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Form Demo',theme: new ThemeData(
            hintColor: Colors.white,primarySwatch: Colors.yellow,),home: new MyHomePage(title: 'Flutter Form Demo'),);
      }
    }
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key,this.title}) : super(key: key);
      final String title;
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }

    Contact newContact = new Contact();
    final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
    final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

    class _MyHomePageState extends State<MyHomePage> {

      bool isValidEmail(String input) {
        final RegExp regex = new RegExp(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-] 
    {0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$");
        return regex.hasMatch(input);
      }

      double itemsHeight = 30;

      Widget getTextField({String hint = 'Ingredients',Widget suffix}) {
    
        return Container(
          height: itemsHeight,child: TextField(
            decoration: Inputdecoration(
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.zero,borderSide: BorderSide(color: Colors.white,width: 1)),hintText: hint,contentPadding: EdgeInsets.all(
                  0),// change each value,and set 0 remainding ones.
              suffixIcon: suffix,expands: false,maxLines: 1,controller: TextEditingController(),);
       }

       @override
      Widget build(BuildContext context) {
        return new Scaffold(
          key: _scaffoldKey,appBar: new AppBar(
            title: new Text('Contact'),backgroundColor: Color(0xFFF6D580),backgroundColor: Colors.black,body: new SafeArea(
              top: false,bottom: false,child: new Form(
                  key: _formKey,autovalidate: true,child: new Container(
                      padding: const EdgeInsets.only( top: 20.0),child: SingleChildScrollView(
                          child: new Column(
                            children: <Widget>[

                              new Text('Contact Us',style: TextStyle(fontSize: 25.0,color: const 
    Color(0xFFffffff)),textAlign: TextAlign.center),new TextFormField(
                                style: TextStyle(
                                  color: Colors.white,decoration: const Inputdecoration(
                                  icon: const Icon(Icons.person,color: Colors.grey,hintText: 'Enter your first and last name',labelText: 'Your Name',inputFormatters: [new LengthLimitingTextInputFormatter(30)],onSaved: (val) => newContact.name = val,decoration: const Inputdecoration(
                                  icon: const Icon(Icons.phone,hintText: 'Enter a phone number',labelText: 'Your phone',keyboardType: TextInputType.phone,inputFormatters: [
                                  new WhitelistingTextInputFormatter(
                                      new RegExp(r'^[()\d -]{1,15}$')),],validator: (val) => isValidPhoneNumber(val)
                                    ? null
                                    : 'Phone number must be entered as (###)###-####',onSaved: (val) => newContact.phones = val,decoration: const Inputdecoration(
                              icon: const Icon(Icons.email,hintText: 'Enter a email address',labelText: 'Your email',keyboardType: TextInputType.emailAddress,validator: (val) => isValidEmail(val)
                                ? null
                                : 'Please enter a valid email address',onSaved: (val) => newContact.emails = val,new TextFormField(
                            style: TextStyle(
                              color: Colors.white,decoration: const Inputdecoration(
                              labelText: 'Message subject',onSaved: (val) => newContact.messagesubject = val,decoration: const Inputdecoration(
                              labelText: 'Message text',onSaved: (val) => newContact.messagetext = val,new Container(
                              padding: const EdgeInsets.only( top: 20.0),child: new RaisedButton(
                                color: const Color(0xFFF6D580),child: const Text('Send',style: TextStyle(fontSize: 20.0),onpressed: _submitForm,)),))))),);
  }
}

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)