32

I want to display the text over the images in Listview. I am able to see the Images and text but text will showing at left top corner. I want to display it on each text over the each images. Below is my code. Please help me

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,
    );
  }
}
Google
  • 2,183
  • 3
  • 27
  • 48

6 Answers6

69

You can use a Stack widget for that:

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

PhotosList class:

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)),
                ]
            );
            }
        );
    }
}
Bostrot
  • 5,767
  • 3
  • 37
  • 47
  • Yes but how can i put the text from arraylist. can you please modify my above code ? – Google Jul 02 '18 at 13:26
  • Simply replace the class I just added with the class in your code. – Bostrot Jul 02 '18 at 13:32
  • Showing me the error in Center(Text(photos[int].title) line. Too many positional arguments: 0 expected, but 1 found – Google Jul 02 '18 at 13:36
  • @Google My mistake. Added the parameter to the example above. – Bostrot Jul 02 '18 at 13:39
  • Thanks Man for gave me the answer – Google Jul 03 '18 at 12:02
  • Can you please help me on below question. how to parse "Listdata". https://stackoverflow.com/questions/50809772/how-to-parse-the-json-data-and-display-it-in-listview-in-flutter/50812530#50812530 – Google Jul 06 '18 at 04:35
  • To preserve the Boxfit settings of your image widget, add `fit: Stackfit.expand` to your Stack widget. I found this solution here: https://stackoverflow.com/a/61594620/6424258 – Rivers Cuomo Jun 03 '21 at 13:12
19

try this:

Container(
    height: 190.0,
    width: MediaQuery.of(context).size.width - 100.0,
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(5),
        color: Colors.blue,
        image: const DecorationImage(
            image: NetworkImage(
                "https://storage.googleapis.com/gd-wagtail-prod-assets/original_images/MDA2018_inline_03.jpg"),
            fit: BoxFit.fill)),
    child: const Center(
      child: Text('test'),
    ),
  ),
  • 2
    And if you would like to gray out (darken) the image slightly, you can add a " colorFilter: " option to the DecorationImage. – GraSim May 29 '22 at 12:38
13

I find this worked a bit better and you don't need the Center widget:

Stack(
    alignment: Alignment.center,
    children: <Widget>[
        yourImageWidget,
        Text("someText"),
    ]
)
Nick
  • 186
  • 1
  • 5
5

Just want to add a small example of 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),
            )),
      ],
    ),
  ),
);

Output:

enter image description here

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
4

try this

enter image description here

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,
              )),
        ]),
      ]),
    );

to set text bottom

                mainAxisAlignment: MainAxisAlignment.end,

to set text top

                mainAxisAlignment: MainAxisAlignment.start,

to set text center

                mainAxisAlignment: MainAxisAlignment.center,
Sandeep Pareek
  • 1,636
  • 19
  • 21
0

Example of Text over background-image using Stack.

   body: SafeArea(
  child: Stack(
      children:[
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("Assets/splash_images/splash.png",),fit: BoxFit.cover,

            ),
          ),
        ),
        Column(
          children: const [
            Center(
              child: Text("Text is Here ",style:TextStyle(fontSize: 20),)
              ,
            )
          ],
        )

      ]),
)

**

**

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 08 '22 at 23:03