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 ();
},
而且...那是一個包裹!我希望這對您有所幫助,您學到了一些新的東西。如果您願意,請考慮給出此倉庫。如果您有任何疑問,您肯定可以通過我的社交來吸引我。
一切順利?