MemeAppFlutter
1.0.0



代码:home_page.dart
从memesapi解析数据
Future < MemesModel > getMemesApi () async {
final response =
await http. get ( Uri . parse ( "https://api.imgflip.com/get_memes" ));
var data = jsonDecode (response.body);
if (response.statusCode == 200 ) {
return MemesModel . fromJson (data);
} else {
return MemesModel . fromJson (data);
}
} class _HomePageState extends State < HomePage > {
late Future < MemesModel > memes;
@override
void initState () {
super . initState ();
memes = getMemesApi ();
}body : FutureBuilder < MemesModel >(
future : memes,
builder : (context, snapshot) {snapshot.hasData , snapshot.harError )snapshot.hasData呈现UI,则否则如果snapshot.hasError显示错误,否则会呈现圆形ProgressIndicator,即等待获取数据的同时。 DynamicHeightGridView (
crossAxisCount : 2 ,
mainAxisSpacing : 10 ,
crossAxisSpacing : 25 ,
itemCount :
//nullcheck operator
snapshot.hasData ? snapshot.data ! .data ! .memes ! .length : 1 ,
builder : (context, index) {
//data fetched successfully
if (snapshot.hasData) {
//render UI here
} //data couldn't be fetched due to some error
else if (snapshot.hasError) {
return Center (
child : Text ( "Error Occured : ${ snapshot . error }" ),
); //waiting for data to be fetched (just the way youtube videos show circular progressor while buffering)
else {
return const Center (
child : CircularProgressIndicator (
color : Colors .teal,
));
}提供商是一种国家管理工具,您可以在此处参考更多有关它的信息:ProvidEreXample
注意:可能需要一些时间才能了解提供商,我的案子也不例外。 (请记住:一夜之间没有什么,好事需要时间!)
我们使用提供商有2个基本要求。
案例1:增量/减少主页上的CART图标上的计数器值(请参阅上面的图像)。
案例2:构建购物车页面。
案例1:在这里增加/减少计数器代码:cart_counter_provider.dart
import 'package:flutter/cupertino.dart' ;
class CartCounterProvider extends ChangeNotifier {
int cartCount;
CartCounterProvider ({ this .cartCount = 0 });
int get getCartCount => cartCount;
void increment () {
cartCount += 1 ;
notifyListeners ();
}
void decrement () {
cartCount -= 1 ;
notifyListeners ();
}
}接下来,我们什么时候需要提供商?,什么时候按下按钮!
代码在这里
context. read < CartCounterProvider >(). increment ();代码在这里
//just inside the build method this cartCounter will watch the value of the counter
//button pressed -> increment() method called using provider -> cartCounter watches the value and updates accordingly
int cartCounter = context. watch < CartCounterProvider >().getCartCount;使用阅读和观看是一种方法。另一个是使用您制作的提供商类的实例,让我们讨论案例2的方法。
案例2:构建购物车页面。
注意:在实施之前,请始终尝试在实施之前定义功能。
购物车页面的计划很简单:
显示购物车的提供者类(MemecartProvider)
代码meme_cart_provider.dart
//read below about CartCardModel first
import 'package:memeapp/models/cart_card_model.dart' ;
import 'package:flutter/cupertino.dart' ;
class MemeCartProvider extends ChangeNotifier {
//now it's convenient for us to display the memes, we just need a list of CartCardModel!
//each instance of this class will have the respective id, imageURL, and name of the meme.
//We just need to traverse and display this list in the cart page, thats it!
//_cartList will have the id, imageURL, name of only those memes that are added to cart by user
final List < CartCardModel > _cartList = < CartCardModel > [];
//memesIdList will only contain the meme ID's which will be used to add/remove memes from the cart
//also used to prevent duplicates
List < String > ? memesIdList = < String > [];
List < CartCardModel > get getCartList => _cartList;
List < String > ? get getMemesIdList => memesIdList;
void addItem ( CartCardModel addThisItem) {
_cartList. add (addThisItem);
notifyListeners ();
}
void removeItem ( String memeId) {
_cartList. removeWhere ((element) => element.id == memeId);
memesIdList ! . remove (memeId);
notifyListeners ();
}
}cartcardmodel cart_card_model.dart
//each instance of this class (CartCardModel) will have the info of id, imageURL, and name.
//it will now be easier to display the memes in the cart page
class CartCardModel {
String id;
String ? nameCart;
String ? imageUrlCart;
CartCardModel ({
required this .id,
this .nameCart,
this .imageUrlCart,
});
}现在,它方便我们在购物车页面上渲染模因。我们只是遍历列表并相应地显示项目。
但是,我们将如何确保仅渲染用户添加的这些项目?提供者再次!
代码cart_page.dart
//define an instance of MemeCartProvider class like this inside the build method
Widget build ( BuildContext context) {
var memeCartProvider = Provider . of < MemeCartProvider >(context);代码在这里
//wrap the Listview.builder with CONSUMER<MemeCartProvider>
Consumer < MemeCartProvider >(
builder : (context, value, child) {
//ListView will traverse CartCardModel list and render memes accordingly
return ListView . builder (
//itemCount is simply the length of the list.
itemCount : value.getMemesIdList ! .length,
itemBuilder : ((context, index) {
object / instance of CartCardModel class using MemeCartProvider
CartCardModel cartObject = value.getCartList[index];代码在这里
//render the image using cartObject
Image . network (
"${ cartObject . imageUrlCart }" ,
width : 140 ,
),
//render the name using cartObject
Text (
//limiting name to 20 characters
cartObject.nameCart ! .length > 20
? "${ cartObject . nameCart !. substring ( 0 , 20 )}..."
: "${ cartObject . nameCart }" ,最后但并非最不重要的一点,我们需要实现删除功能
onPressed : () {
//we will remove the item from the list
value. removeItem (cartObject.id);
//why this line? you might've guessed it already, if not, dont worry
//remember we incrementes the counter value when user added items to the cart
//now user is deleting items, hence we need to decreament that counter value too!, right?
context. read < CartCounterProvider >(). decrement ();
},
而且...那是一个包裹!我希望这对您有所帮助,您学到了一些新的东西。如果您愿意,请考虑给出此仓库。如果您有任何疑问,您肯定可以通过我的社交来吸引我。
一切顺利?