Home > Software design >  How to display a snackbar after entering text in a TextField?
How to display a snackbar after entering text in a TextField?

Time:05-10

I have a text field. I need a snackbar to appear after the user has finished typing words into it after 300ms.Snackbar should appear in the middle of the screen. How can I make the snackbar appear 300ms after the user has stopped typing in the text field? My code:

final textController = TextEditingController();
....
child: TextField(
controller: textController,
onChanged: (value) {},
)

CodePudding user response:

Similar to other answer, but will appear after user stopped typing and not when user submits the TextField :

  Timer? t;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextField(
          onChanged: (v) {
            t?.cancel();
            t = Timer(const Duration(milliseconds: 300), () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('im a snackbar'),
                ),
              );
            });
          },
        ),
      ),
    );
  }

CodePudding user response:

Please check the following code and see if it helps.

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(const SnackBarDemo());

class SnackBarDemo extends StatelessWidget {
  const SnackBarDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SnackBar Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('SnackBar Demo'),
        ),
        body: const SnackBarPage(),
      ),
    );
  }
}

class SnackBarPage extends StatelessWidget {
  const SnackBarPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Center(
        child: TextField(
          onEditingComplete: () {
            final snackBar = SnackBar(
              content: const Text('Yay! A SnackBar!'),
              action: SnackBarAction(
                label: 'Undo',
                onPressed: () {
                  // Some code to undo the change.
                },
              ),
            );

            Timer(Duration(milliseconds: 300), () {
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            });
          },
        ),
      ),
    );
  }
}
  • Related