What skills are there in flutter development

Not much to say, when developing, the following are some skills in Flutter development:

  1. Use StatefulWidgets to manage state. StatefulWidget allows you to easily manage the state of your application without having to track it manually.
class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      value: _isChecked,
      onChanged: (bool value) {
        setState(() {
          _isChecked = value;
        });
      },
    );
  }
}
  1. Use LayoutBuilder and ConstrainedBox to create adaptive layouts. This ensures that your application will work properly on various devices.
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return ConstrainedBox(
          constraints: BoxConstraints(
            minWidth: constraints.maxWidth,
            minHeight: constraints.maxHeight,
            maxWidth: constraints.maxWidth,
            maxHeight: constraints.maxHeight,
          ),
          child: Text('Hello, World!'),
        );
      },
    );
  }
}
  1. Use async/await for asynchronous code. This can make your code more readable without using callback functions.
class MyWidget extends StatelessWidget {
  Future<void> _doSomethingAsync() async {
    await Future.delayed(Duration(seconds: 1));
    print('Done!');
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: () async {
        await _doSomethingAsync();
      },
      child: Text('Do something'),
    );
  }
}
  1. Use WidgetsBindingObserver to monitor the application lifecycle. This allows you to perform specific actions when the application starts, suspends, and resumes.
class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('AppLifecycleState: $state');
  }

  @override
  Widget build(BuildContext context) {
    return Text('Hello, World!');
  }
}
  1. Use InheritedWidget to share data. This makes it easier to pass data around your application.
class MyInheritedWidget extends InheritedWidget {
  final int count;
  final Widget child;

  MyInheritedWidget({Key key, this.count, this.child}) : super(key: key, child: child);

  static MyInheritedWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
  }

  @override
  bool updateShouldNotify(MyInheritedWidget oldWidget) {
    return count != oldWidget.count;
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyInheritedWidget(
      count: 42,
      child: Text('Hello, World!'),
    );
  }
}

class MyOtherWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final myInheritedWidget = MyInheritedWidget.of(context);
    return Text('Count: ${myInheritedWidget.count}');
  }
}
  1. Use Keys to manage Widget state. Keys allow you to preserve the state of a widget when rebuilding it, so that users don't lose their data.
class MyWidget extends StatefulWidget {
  final Key key;

  MyWidget({this.key}) : super(key: key);

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

class _MyWidgetState extends State<MyWidget> {
  String _text = '';

  @override
  Widget build(BuildContext context) {
    return TextField(
      key: widget.key,
      onChanged: (value) {
        setState(() {
          _text = value;
        });
      },
      decoration: InputDecoration(
        hintText: 'Enter some text',
      ),
    );
  }
}
  1. Use Navigator to manage page routing. Navigator lets you easily jump to another page and process the results when you return.
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () async {
            final result = await Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => MyOtherPage()),
            );
            print('Result: $result');
          },
          child: Text('Go to Other Page'),
        ),
      ),
    );
  }
}

class MyOtherPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Other Page'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context, 'Hello, World!');
          },
          child: Text('Go Back'),
        ),
      ),
    );
  }
}
  1. Use MediaQuery to get device information. MediaQuery lets you get information about the size, orientation, and pixel density of the device screen.
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final size = mediaQuery.size;
    final orientation = mediaQuery.orientation;
    final devicePixelRatio = mediaQuery.devicePixelRatio;
    return Text('Size: $size\nOrientation: $orientation\nDevice Pixel Ratio: $devicePixelRatio');
  }
}
  1. Use Flutter packages to get powerful third-party libraries. Flutter packages allow you to easily add libraries written by others to your application to implement complex functionality.
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: () {},
      icon: Icon(FontAwesomeIcons.heart),
    );
  }
}
  1. Use the Flutter Inspector to debug your app. Flutter Inspector is a powerful debugging tool that allows you to view the state and hierarchy of your application and quickly identify problems.

  2. Use Flutter's animation library to create animation effects. Flutter's animation library is very powerful, allowing you to create a variety of animation effects, including translation, scaling, rotation, transparency, and more.


class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 1),
      vsync: this,
    );
    _animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(_controller);
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: _animation,
      child: Text('Hello, World!'),
    );
  }
}
  1. Use Flutter's themes to customize the look and feel of your app. Themes for Flutter allow you to easily change your app's colors, fonts, size, and more.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Roboto',
        textTheme: TextTheme(
          bodyText1: TextStyle(fontSize: 16.0),
          bodyText2: TextStyle(fontSize: 14.0),
          button: TextStyle(fontSize: 16.0),
        ),
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: Text(
          'Hello, World!',
          style: Theme.of(context).textTheme.bodyText1,
        ),
      ),
    );
  }
}
  1. Use Flutter's layout library to create complex layouts. Flutter's layout library includes various widgets, such as Row, Column, Stack, and Expanded, which allow you to easily create complex layouts.
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Title'),
        SizedBox(height: 8.0),
        Row(
          children: [
            Icon(Icons.star),
            Icon(Icons.star),
            Icon(Icons.star),
            Icon(Icons.star),
            Icon(Icons.star_border),
          ],
        ),
        SizedBox(height: 8.0),
        Text('Description'),
        SizedBox(height: 8.0),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('Price'),
            RaisedButton(
              onPressed: () {},
              child: Text('Buy Now'),
            ),
          ],
        ),
      ],
    );
  }
}
  1. Use Flutter's internationalization and localization support to support multiple languages. Flutter's internationalization and localization support lets you support multiple languages ​​in your app so your app can be used globally.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', 'US'),
        const Locale('zh', 'CN'),
      ],
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).title),
      ),
      body: Center(
        child: Text(AppLocalizations.of(context).helloWorld),
      ),
    );
  }
}

class AppLocalizations {
  static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

  final String title;
  final String helloWorld;

  AppLocalizations({this.title, this.helloWorld});

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }
}

class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);

  @override
  Future<AppLocalizations> load(Locale locale) async {
    final bundle = await rootBundle.loadString('assets/i18n/${locale.languageCode}.json');
    final map = json.decode(bundle);
    return AppLocalizations(
      title: map['title'],
      helloWorld: map['hello_world'],
    );
  }

  @override
  bool shouldReload(_AppLocalizationsDelegate old) => false;
}
  1. Use Flutter's testing library to test your app. Flutter's testing library allows you to easily write and run various tests to ensure the quality of your application.
void main() {
  group('MyWidget', () {
    testWidgets('should display text', (WidgetTester tester) async {
      await tester.pumpWidget(MyWidget());
      expect(find.text('Hello, World!'), findsOneWidget);
    });

    testWidgets('should change text on tap', (WidgetTester tester) async {
      await tester.pumpWidget(MyWidget());
      await tester.tap(find.byType(RaisedButton));
      await tester.pump();
      expect(find.text('Goodbye, World!'), findsOneWidget);
    });
  });
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String _text = 'Hello, World!';

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(_text),
        RaisedButton(
          onPressed: () {
            setState(() {
              _text = 'Goodbye, World!';
            });
          },
          child: Text('Change Text'),
        ),
      ],
    );
  }
}

These are some tips in Flutter development that can make our development process easier and more efficient. Those who have the pursuit can collect and study! Welcome to add.

at last! When you're afraid to jump, that's when you should dance, or you'd never dance. To encourage each other

Guess you like

Origin blog.csdn.net/qq_28563283/article/details/130685530