Dasar Flutter untuk Pemula (Bagian VI)

Saat Anda membuat berbagai formulir (misalnya: pendaftaran atau login) di Flutter, Anda tidak perlu repot menyesuaikan komponen, karena Anda dapat mengubah bidang formulir apa pun agar sesuai dengan gaya Anda.





Selain penyesuaian, Flutter menyediakan penanganan kesalahan dan kemampuan validasi bidang formulir.





Dan hari ini kita akan mencoba membahas topik ini dengan contoh kecil.





Ayo pergi!





Rencana kita
  • Bagian 1  - pengantar pembangunan, lampiran pertama, konsep negara;





  • Bagian 2  - file pubspec.yaml dan menggunakan flutter pada baris perintah;





  • Bagian 3  - BottomNavigationBar dan Navigator;





  • Bagian 4  - MVC. Kami akan menggunakan pola khusus ini sebagai salah satu yang paling sederhana;





  • Bagian 5 - paket http. Pembuatan kelas Repositori, permintaan pertama, daftar posting;





  • Bagian 6 (artikel saat ini) - Bekerja dengan formulir, bidang teks, dan membuat posting.





  • Bagian 7 - bekerja dengan gambar, menampilkan gambar dalam bentuk kisi, menerima gambar dari jaringan, menambahkan gambar Anda sendiri ke aplikasi;





  • Bagian 8 - membuat tema Anda sendiri, menambahkan font dan animasi khusus;





  • Bagian 9 - sedikit tentang pengujian;





Pembuatan formulir: menambahkan pos

Pertama, HomePage



mari tambahkan tombol ke halaman kita di mana kita akan menambahkan posting baru:





@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Post List Page"),
    ),
    body: _buildContent(),
    //       FloatingActionButton
    floatingActionButton: FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () {

      },
    ),
  );
}
      
      



Selanjutnya, mari kita buat halaman baru di file post_add_page.dart



:






import 'package:flutter/material.dart';

class PostDetailPage extends StatefulWidget {
  @override
  _PostDetailPageState createState() => _PostDetailPageState();
}

class _PostDetailPageState extends State<PostDetailPage> {
  
  // TextEditingController'       
  final TextEditingController titleController = TextEditingController();
  final TextEditingController contentController = TextEditingController();
  
  // _formKey    
  final _formKey = GlobalKey<FormState>();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Post Add Page"),
        actions: [
          //    AppBar
          IconButton(
            icon: Icon(Icons.check),
            onPressed: () {
              //    
              if (_formKey.currentState!.validate()) {
                //     c  
              }
            },
          )
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(15),
        child: _buildContent(),
      ),
    );
  }
  Widget _buildContent() {
    //  
    return Form(
      key: _formKey,
      //     
      child: Column(
        children: [
          //    
          TextFormField(
            //    ,
            //    (hint)
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.face),
                hintText: ""
            ),
            //    TextEditingController
            controller: titleController,
            //  validator -  ,
            //   null   
            //    
            validator: (value) {
              //      2 
              if (value == null || value.isEmpty) {
                return " ";
              }
              if (value.length < 3) {
                return "     3 ";
              }
              return null;
            },
          ),
          //    
          SizedBox(height: 10),
          // Expanded ,   
          //       
          Expanded(
            child: TextFormField(
              // maxLines: null  expands: true 
              //        
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "",
              ),
              //    TextEditingController
              controller: contentController,
              //    
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return " ";
                }
                return null;
              },
            ),
          )
        ],
      ),
    );
  }
}
      
      



Jangan lupa untuk menambahkan transisi ke halaman formulir:





floatingActionButton: FloatingActionButton(
   child: Icon(Icons.add),
   onPressed: () {
      Navigator.push(context, MaterialPageRoute(
         builder: (context) => PostDetailPage()
      ));
   },
),
      
      



Luncurkan dan klik tombol:





! .





. , .





100%- Flutter Dart :





  • Flutter 2.0.6





  • Dart SDK version: 2.12.3





null safety. , .





null safety. :





// !   ,   100% 
//  currentState   null 
_formKey.currentState!.validate()
      
      



null safety Dart , .





POST .





POST

POST, , HTTP .





Post



:





class Post {
  //    private
  //     
  final int? _userId;
  final int? _id;
  final String? _title;
  final String? _body;

  //  getters   
  //      
  int? get userId => _userId;
  int? get id => _id;
  String? get title => _title;
  String? get body => _body;

  //     
  Post(this._userId, this._id, this._title, this._body);

  // toJson()  Post   JSON
  String toJson() {
    return json.encode({
      "title": _title,
      "content": _body
    });
  }

  // Dart      
  //    Post.fromJson(json) -  
  //         
  //  ,  dynamic 
  //    : String, int, double  ..
  Post.fromJson(Map<String, dynamic> json) :
    this._userId = json["userId"],
    this._id = json["id"],
    this._title = json["title"],
    this._body = json["body"];
}

//      
abstract class PostAdd {}

//  
class PostAddSuccess extends PostAdd {}
// 
class PostAddFailure extends PostAdd {}
      
      



Repository



:





//    
Future<PostAdd> addPost(Post post) async {
  final url = Uri.parse("$SERVER/posts");
  //  POST ,   
  //  JSON   
  final response = await http.post(url, body: post.toJson());
  //     
  if (response.statusCode == 201) {
    // ,   
    return PostAddSuccess();
  } else {
    //  
    return PostAddFailure();
  }
}
      
      



PostController



:





//  
//  addPost   callback,
//      
void addPost(Post post, void Function(PostAdd) callback) async {
  try {
    final result = await repo.addPost(post);
    //   
    callback(result);
  } catch (error) {
    //  
    callback(PostAddFailure());
  }
}
      
      



PostAddPage



:





class PostDetailPage extends StatefulWidget {

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

//     StateMVC
class _PostDetailPageState extends StateMVC {

  // _controller   null
  PostController? _controller;

  //  PostController
  _PostDetailPageState() : super(PostController()) {
    _controller = controller as PostController;
  }

  // TextEditingController'       
  final TextEditingController titleController = TextEditingController();
  final TextEditingController contentController = TextEditingController();

  // _formKey    
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Post Add Page"),
        actions: [
          //    AppBar
          IconButton(
            icon: Icon(Icons.check),
            onPressed: () {
              //    
              if (_formKey.currentState!.validate()) {
                //  
                //    TextEditingController'
                final post = Post(
                  -1, -1, titleController.text, contentController.text
                );
                //  
                _controller!.addPost(post, (status) {
                  if (status is PostAddSuccess) {
                    //     
                    //     
                    // 
                    Navigator.pop(context, status);
                  } else {
                    //      
                    // SnackBar -  
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text("    "))
                    );
                  }
                });
              }
            },
          )
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(15),
        child: _buildContent(),
      ),
    );
  }

  Widget _buildContent() {
    //  
    return Form(
      key: _formKey,
      //     
      child: Column(
        children: [
          //    
          TextFormField(
            //    ,
            //    (hint)
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.face),
                hintText: ""
            ),
            //  TextEditingController
            controller: titleController,
            //  validator -  ,
            //   null   
            //    
            validator: (value) {
              //      2 
              if (value == null || value.isEmpty) {
                return " ";
              }
              if (value.length < 3) {
                return "     3 ";
              }
              return null;
            },
          ),
          //    
          SizedBox(height: 10),
          // Expanded ,   
          //       
          Expanded(
            child: TextFormField(
              // maxLines: null  expands: true
              //    
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "",
              ),
              //  TextEditingController
              controller: contentController,
              //    
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return " ";
                }
                return null;
              },
            ),
          )
        ],
      ),
    );
  }

}
      
      



:









  1. ,





  2. , .





, PostListPage



:





floatingActionButton: FloatingActionButton(
  child: Icon(Icons.add),
  onPressed: () {
    // then   Future
    //       
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => PostDetailPage()
    )).then((value) {
      if (value is PostAddSuccess) {
        // SnackBar -  
        ScaffoldMessenger.of(context).showSnackBar(
         SnackBar(content: Text("   "))
        );
      }
    });
  },
),
      
      



:





JSONPlaceholder .





Saya harap saya telah meyakinkan Anda bahwa bekerja dengan formulir di Flutter sangat mudah dan hampir tidak memerlukan usaha.





Sebagian besar kode membuat permintaan POST ke server dan menangani kesalahan.





tautan yang bermanfaat





  • Kode sumber di Github





  • Membangun formulir dengan validasi (EN)





  • Dart null keselamatan null





Kode bagus semuanya)








All Articles