Flutter TextInput 输入错误时提示文字内容

9 min read

TextField > decoration > errorText

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            children: [
              TextField(
                decoration: InputDecoration(
                  errorText: _errorText,
                  labelText: 'Enter your name',
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String get _errorText {
    if (_name?.length == 0) return 'Name cannot be empty';
    return null;
  }

  String get _name => null;