These 10 widgets that every developer must know

A cat that can make coffee 2021-05-03 19:17:01
widgets developer know


original text

genotechies.medium.com/these-10-fl…

These are what we are going to discuss widgets:

  • Dismissible
  • SizedBox
  • Draggable
  • Flexible
  • MediaQuery
  • Spacer
  • AnimatedIcon
  • Placeholder
  • RichText
  • ReorderableListView

Text

Dismissible

Sliding and hiding are common in mobile applications UI Pattern . To be in Flutter Do this , have access to Dismissible widget. It has one child,background and key . It will detect sliding gestures and animations child The widget . You can also exchange two-way and vertical . You can use more attributes in your own way . You can try it by copying and pasting the code below .

class _MyHomePageState extends State<MyHomePage> {
List<String> _values = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
@override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: _values.length,
padding: const EdgeInsets.all(5.0),
separatorBuilder: (context, index) => Divider(
color: Colors.black,
),
itemBuilder: (context, index) {
return Dismissible(
key: Key('item ${_values[index]}'),
onDismissed: (DismissDirection direction) {
if (direction == DismissDirection.startToEnd) {
print("Selected Item");
} else {
print('Delete item');
}
setState(() {
_values.removeAt(index);
});
},
child: ListTile(
leading: Icon(Icons.email, size: 50),
title: Text(_values[index]),
),
);
}
);
}
}
 Copy code 

SizedBox

This is an example of a widget . When you have a widget , It should be a fixed size . for example , The size of a button should be width = 100px and height = 50px. You need to package the buttons in SizedBox in . Here's the class constructor .

const SizedBox(
{Key key,
double width,
double height,
Widget child}
)
 Copy code 

Draggable

In many applications , We can see the drag option , In e-mail , Document drag . With this Flutter The widget , It's easy to do this . ad locum , We drag data . Here I pass a message from Draggable To DragTarget String . Then you need to explain what data you're passing , Sub attributes display your data .DragTarget The goal is to drag Draggable Our landing area . There are three main calling methods .

  • onwillAccept: To test whether the moving target can accept the data
  • onAccept: Call a valid draggable area
  • onLeave: Call... When the region fails

Flexible

Most of the time , We use rows and columns to display a set of child widgets . But they need to be flexible in size to show relevance to their parents . You just need to wrap all the child widgets in one flexible widget .Flex Value determines how much space each child element gets . When you change the screen size , It doesn't change the proportion of children .

child: Column(
children: <Widget>[
Flexible(
flex: 3,
child: Container(
color: Colors.red,
)
),
Flexible(
flex: 1,
child: Container(
color: Colors.green,
)
),
Flexible(
flex: 2,
child: Container(
color: Colors.blue,
)
),
],
)
 Copy code 

MediaQuery

If your goal is to run your app on your phone and tabs , Your application needs to support different user interface sizes . Besides , Sometimes users have their own UI expect , Such as font size or small , Direction , Filling, etc . Use this MediaQuery, You can get screen size information and user preferences , And build the layout based on these details .

const MediaQueryData({
this.size = Size.zero,
this.devicePixelRatio = 1.0,
this.textScaleFactor = 1.0,
this.platformBrightness = Brightness.light,
this.padding = EdgeInsets.zero,
this.viewInsets = EdgeInsets.zero,
this.systemGestureInsets = EdgeInsets.zero,
this.viewPadding = EdgeInsets.zero,
this.alwaysUse24HourFormat = false,
this.accessibleNavigation = false,
this.invertColors = false,
this.highContrast = false,
this.disableAnimations = false,
this.boldText = false,
this.navigationMode = NavigationMode.traditional,
})
 Copy code 

This is an example of extracting screen size .

MediaQueryData deviceInfo = MediaQuery.of(context);
 Copy code 

Output

I/flutter ( 6508): size: Size(360.0, 592.0)
I/flutter ( 6508): padding: EdgeInsets(0.0, 24.0, 0.0, 0.0)
I/flutter (6508) : Size: Size (360.0,592.0) i/flutter (6508) : padding: EdgeInsets (0.0,24.0,0.0,0.0)
 Copy code 

Spacer

This is another widget , You'd better use it in pre customization . In one line , We can use MainAxisAlignment Define the space between children . But use Spacer The widget , You can do more . Just add a spacer between the other widgets . then children Expand to create extra space . There is one flex Property to determine the relative size .

SizedBox(
height: 50,
child: Row(
children: <Widget>[
Container(
width: 50,
color: Colors.red,
),
Spacer(flex: 2,),
Container(
width: 50,
color: Colors.green,
),
Spacer(flex: 1,),
Container(
width: 50,
color: Colors.blue,
),
Container(
width: 50,
color: Colors.yellow,
),
],
),
);
 Copy code 

AnimatedIcon

There's already a huge set of icons already in the frame . There are also animated icons , You can use... In your application . To use these , We need a AnimatedIcon The widget . You need to provide icons and main progress attributes .Flutter There are many different animated icons for you to use .

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
void main() => runApp(LogoApp());
class LogoApp extends StatefulWidget {
_LogoAppState createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
bool isPlaying = false;
Animation animation;
AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 500), vsync: this);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: IconButton(
iconSize: 70,
icon: AnimatedIcon(
icon: AnimatedIcons.play_pause,
progress: controller,
),
onPressed: () => _onpressed(),
)),
),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
_onpressed() {
setState(() {
isPlaying = !isPlaying;
isPlaying ? controller.forward() : controller.reverse();
});
}
}
 Copy code 

Placeholder

Sometimes you need to work for UI Space reserved for specific components of , Until the view of the component is finally determined . therefore , Instead of keeping a space , We can put it there Plaholder In order to further realize . After you can start implementing it . This will fill in all the space mentioned .

Center(
child: Column(
children: <Widget>[
Container(
child: Placeholder()
),
Expanded(
child: Row(
children: <Widget>[
Flexible(
flex: 1,
child: Placeholder(color: Colors.red,),
),
Flexible(
flex: 4,
child: Placeholder(color: Colors.green,),
),
],
),
)
],
)
),
 Copy code 

RichText

Text is the main part of every application UI One of the components . So font design is very important . You have to pay attention to the style and appearance of the text , Such as text size 、 typeface 、 Patterns, etc . Sometimes you need to show a paragraph that combines different styles . Emphasize in bold , Or in italics , Or underline , Or in different colors , Different font sizes , Or show everything at the same time . You'd better use RichText. Here is an example :

RichText(
text: TextSpan(
style: TextStyle(color: Colors.black, fontSize: 24),
children: <TextSpan>[
TextSpan(text: 'Flutter ', style: TextStyle(color: Colors.red)),
TextSpan(text: 'Placeholder '),
TextSpan(text: 'Widget', style: TextStyle(decoration: TextDecoration.underline, fontStyle: FontStyle.italic))
],
),
)
 Copy code 

ReorderableListView

In our application , We use a list view to display a set of data and scroll through them . Usually , You can't move and change positions in the list .ReorderbaleListView It's the solution . With it , Users can press the item for a long time , And put it in a new place he or she likes . Each item in the list view has a key to identify that item , When moving the item , call onReorder Methods and track moves and changes . Here is an example .

class _TopListState extends State<TopList> {
List<String> topMovies = [
"It Happened One Night(1934)",
"Black Panther(2018)",
"Citizen Kane(1941)",
"Parasite (Gisaengchung)(2019)",
"Avengers: Endgame(2019)",
"The Wizard of Oz(1939)",
"Casablanca(1942)",
"Knives Out(2019)"
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("ReorderableListView Example"),
),
body: ReorderableListView(
onReorder: (int oldIndex, int newIndex) {},
children: getListItems(),
),
);
}
List<ListTile> getListItems() =>
topMovies
.asMap()
.map((i, item) => MapEntry(i, buildTenableListTile(item, i)))
.values
.toList();
ListTile buildTenableListTile(String item, int index) {
return ListTile(
key: ValueKey(item),
title: Text(item),
leading: Text("${index + 1}"),
);
}
}
 Copy code 

Cat elder brother

ducafecat.tech/

github.com/ducafecat

In the past

Open source

GetX Quick Start

github.com/ducafecat/g…

News client

github.com/ducafecat/f…

strapi Manual translation

getstrapi.cn

Wechat discussion group ducafecat

Series collection

translation

ducafecat.tech/categories/…

Dart Fundamentals of programming language

space.bilibili.com/404904528/c…

Flutter Zero Basics

space.bilibili.com/404904528/c…

Flutter The actual combat starts from scratch News client

space.bilibili.com/404904528/c…

Flutter Component development

space.bilibili.com/404904528/c…

Flutter Bloc

space.bilibili.com/404904528/c…

Flutter Getx4

space.bilibili.com/404904528/c…

Docker Yapi

space.bilibili.com/404904528/c…

版权声明
本文为[A cat that can make coffee]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503191542537L.html

  1. CSS layout
  2. Application scenario explanation of Vue dynamic component
  3. Redux learning notes 04 -- using multiple reducers to manage data
  4. After three months of typescript writing, what have I learned?
  5. Node family - what is a callback?
  6. React -- a simple implementation of render & create element
  7. JS learning simple usage of jquery
  8. Seamless love
  9. 小白前端入门笔记(12),设置哑链接
  10. Small white front-end entry notes (12), set dumb links
  11. Vue2. X opens composition API and TSX
  12. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  13. Flex learning notes
  14. The most essential closure article in the eastern hemisphere
  15. 2021-05-03 hot news
  16. Sword finger offer -- reverse order pair in array (JS Implementation)
  17. Working process of scaffold
  18. Use decorator mode to strengthen your fetch
  19. [JS] scope (Introduction)
  20. Employment information statistics network (interface document)
  21. Analysis of MVC
  22. [middle stage] please stay and join me in the backstage
  23. Understanding front end garbage collection
  24. [continuous update] front end special style implementation
  25. Flutter product analysis and package reduction scheme
  26. XPath positioning
  27. 前端开发css中的flex布局的使用
  28. The use of flex layout in front end development CSS
  29. JQuery核心函数和静态方法
  30. JQuery core functions and static methods
  31. Node family - understanding of blocking and non blocking
  32. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  33. Vue source code analysis (2) initproxy initialization proxy
  34. What's TM called react diff
  35. Summary of common front end data structure
  36. Useeffect in hooks
  37. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  38. Front end notes: virtual Dom and diff of vue2. X
  39. The best code scanning plug-in of flutter
  40. The simplest plug-in for rights management of flutter
  41. 21. Object oriented foundation "problems and solutions of object traversal"
  42. Discussion on hot micro front end: Google AdWords is a real micro front end
  43. Usecallback and usememo for real performance optimization
  44. 【前端圭臬】十一:从规范看 JavaScript 执行上下文(下)
  45. [front end standard] 11: Javascript execution context from the perspective of specification (2)
  46. Hexagonal六角形架构ReactJS的实现方式 - Janos Pasztor
  47. Transaction of spring's reactive / imperative relational database
  48. The implementation of hexagonal hexagonal reactjs Janos pasztor
  49. HTTP状态码:402 Payment Required需要付款 - mozilla
  50. HTTP status code: 402 payment required - Mozilla
  51. Factory mode, constructor mode and prototype mode
  52. Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)
  53. Cocos Quick Start Guide
  54. Comparison of three default configurations of webpack5 modes
  55. A case study of the combination of flutter WebView and Vue
  56. CSS: BFC and IFC
  57. A common error report and solution in Vue combat
  58. JS: this point
  59. JS: prototype chain
  60. JavaScript series -- promise, generator, async and await