flutter form

126 阅读1分钟
// StatefulWidget有状态组件
// TextEditingController 初始化默认值 username
// TextField
// ElevatedButton按钮
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  late TextEditingController _usernameController;
  String username = "zhangsan";
  String password = "";

  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController.fromValue(
      TextEditingValue(
        text: username,
        selection: TextSelection.fromPosition(
          TextPosition(
              affinity: TextAffinity.downstream, offset: username.length),
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 组件销毁时,销毁相关状态值
    _usernameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('TextField'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: ListView(
            children: [
              TextField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  hintText: "用户名",
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) => setState(() {
                  username = value;
                }),
              ),
              const SizedBox(height: 40),
              TextField(
                obscureText: true,
                decoration: const InputDecoration(
                  hintText: "密码",
                  border: OutlineInputBorder(),
                  suffixIcon: Icon(Icons.visibility),
                ),
                onChanged: (value) {
                  password = value;
                },
              ),
              const SizedBox(height: 40),
              ElevatedButton(
                onPressed: () {
                  // ignore: avoid_print
                  print(username);
                  // ignore: avoid_print
                  print(password);
                },
                child: const Text("登录"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}