【问题标题】:How to to display text over the images in Flutter?如何在 Flutter 中的图像上显示文本?
【发布时间】:2018-12-10 17:17:00
【问题描述】:

我想在Listview 中的图像上显示文本。我可以看到图像和文字,但文字会显示在左上角。我想在每个图像上的每个文本上显示它。下面是我的代码。请帮帮我

import 'dart:async';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client.get('url here');
  return compute(parsePhotos, response.body);
}

// A function that will convert a response body into a List<Photo>
List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody);
  return (parsed["data"]["categoryList"] as List)
      .map<Photo>((json) => new Photo.fromJson(json))
      .toList();
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return new MyHomePage();
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new FutureBuilder<List<Photo>>(
      future: fetchPhotos(new http.Client()),
      builder: (context, snapshot) {
        if (snapshot.hasError) print(snapshot.error);
        return snapshot.hasData
            ? new PhotosList(photos: snapshot.data)
            : new Center(child: new CircularProgressIndicator());
      },
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;

  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _buildBody();
  }

  Widget _buildBody() {
    return new Stack(
      children: <Widget>[
        new Positioned(
            child: new Container(
              child: new ListView.builder(
                  itemCount: photos.length,
                  itemBuilder: (context,int){
              return new Text(photos[int].title);
            }
           ),
          )
        ),
        new ListView.builder(
            itemCount: photos.length,
            itemBuilder: (context,int){
              return new CachedNetworkImage(imageUrl: photos[int].url);
            }
        ),
      ],
    );
  }
}

class Photo {
  final int catID;
  final String title;
  final String url;
  final String thumbnailUrl;
  final String description;
  final String webstiteURL;

  Photo(
      {this.catID,
      this.title,
      this.url,
      this.thumbnailUrl,
      this.description,
      this.webstiteURL});

  factory Photo.fromJson(Map<String, dynamic> json) {
    return new Photo(
      catID: json['category_id'] as int,
      title: json['category_name'] as String,
      url: json['category_img'] as String,
      thumbnailUrl: json['thumb_img'] as String,
      description: json['description'] as String,
      webstiteURL: json['website_url'] as String,
    );
  }
}

【问题讨论】:

  • 你的意思是要图片中心的文字吗?
  • 是的。但在 listview 中,请参阅此处的示例屏幕截图。 stackoverflow.com/questions/50855236/…
  • @RaoufRahiche 你知道了吗?
  • 不,假设您有超过三个项目。什么时候放置文本?
  • 你成功了吗? @谷歌

标签: android flutter


【解决方案1】:

您可以为此使用Stack 小部件:

Stack(
    children: <Widget>[
        yourImageWidget,
        Center(child: Text("someText")),
    ]
)

PhotosList 类:

PhotosList({Key key, this.photos}) : super(key: key);

@override
Widget build(BuildContext context) {
    return _buildBody();
}

Widget _buildBody() {
    return new ListView.builder(
            itemCount: photos.length,
            itemBuilder: (context,int){
            return Stack(
                children: <Widget> [
                    new CachedNetworkImage(imageUrl: photos[int].url),
                    Center(child: Text(photos[int].title)),
                ]
            );
            }
        );
    }
}

【讨论】:

  • 是的,但我怎样才能从arraylist 中放置文本。你能修改我上面的代码吗?
  • 只需将我刚刚添加的类替换为您代码中的类即可。
  • 显示 Center(Text(photos[int].title) 行中的错误。位置参数太多:预期为 0,但找到了 1 个
  • @Google 我的错。将参数添加到上面的示例中。
  • 谢谢大佬给我答案
【解决方案2】:

试试这个

Container(
         child: Center(child: Text('test'),),
         height: 190.0,
         width: MediaQuery.of(context).size.width - 100.0,
         decoration: BoxDecoration(
         borderRadius: BorderRadius.circular(5),
         color: Colors.blue,
         image: DecorationImage(
                image: new NetworkImage(
                "https://storage.googleapis.com/gd-wagtail-prod-assets/original_images/MDA2018_inline_03.jpg"
                  ),
          fit: BoxFit.fill
              )
                 ),
              ),

【讨论】:

    【解决方案3】:

    我发现这工作得更好一些,你不需要 Center 小部件:

    Stack(
        alignment: Alignment.center,
        children: <Widget>[
            yourImageWidget,
            Text("someText"),
        ]
    )
    

    【讨论】:

      【解决方案4】:

      只想添加一个Stack Widget的小例子

      return Scaffold(
        appBar: AppBar(
          title: Text("Text Over Image"),
        ),
        body: Center(
          child: Stack(
            children: <Widget>[
              Container(
                alignment: Alignment.center,
                child: Image.network(
                  'https://cdn.pixabay.com/photo/2018/07/11/21/51/toast-3532016_1280.jpg',
                  height: 250,
                  width: double.infinity,
                  fit: BoxFit.cover,
                ),
              ),
              Container(
                  alignment: Alignment.center,
                  child: Text(
                    'Text Message',
                    style: TextStyle(color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: 22.0),
                  )),
            ],
          ),
        ),
      );
      

      输出:

      供参考: https://medium.com/flutterworld/flutter-text-over-image-bb045a129bae

      【讨论】:

        【解决方案5】:

        试试这个

        Card(
              elevation: 4,
              margin: EdgeInsets.fromLTRB(0.0, 4.0, 4.0, 4.0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(4.0),
              ),
              shadowColor: Colors.white,
              color: Colors.white70,
              child: Stack(children: <Widget>[
                Center(
                  child: Image(
                    image: NetworkImage(ApiContent.PREF_IMAGES_PATH +
                        _listMomentListModel[index].filePath),
                  ),
                ),
                Column(mainAxisAlignment: MainAxisAlignment.end, children: [
                  Container(
                      width: double.infinity,
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
                      child: Text(
                        _listMomentListModel[index].title,
                        maxLines: 5,
                        textAlign: TextAlign.center,
                      )),
                ]),
              ]),
            );
        

        设置文字底部

                        mainAxisAlignment: MainAxisAlignment.end,
        

        将文字置顶

                        mainAxisAlignment: MainAxisAlignment.start,
        

        设置文本中心

                        mainAxisAlignment: MainAxisAlignment.center,
        

        【讨论】:

          猜你喜欢
          • 2013-04-15
          • 1970-01-01
          • 2020-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-16
          • 2020-08-01
          相关资源
          最近更新 更多